如何使用 pandas 将多行合并为单行 [英] How to combine multiple rows into a single row with pandas
本文介绍了如何使用 pandas 将多行合并为单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将多行合并为一行,这将是简单的带有空间的连接
I need to combine multiple rows into a single row, that would be simple concat with space
View of my dataframe:
tempx value
0 picture1 1.5
1 picture555 1.5
2 picture255 1.5
3 picture365 1.5
4 picture112 1.5
我希望数据帧像这样转换:(以空格分隔) tempx值
I want the dataframe to be converted like this: (space separated) tempx values
Expected output:
tempx value
0 picture1 picture555 picture255 picture365 picture112 1.5
or
as a python dict
{1.5:{picture1 picture555 picture255 picture365 picture112}}
我尝试过的事情:
df_test['tempx']=df_test['tempx'].str.cat(sep=' ')
这可行,但是它将所有列中的行合并在一起,如下所示:
this works but it combines the rows in all the columns like this:
tempx value
0 picture1 picture555 picture255 picture365 picture112 1.5
1 picture1 picture555 picture255 picture365 picture112 1.5
2 picture1 picture555 picture255 picture365 picture112 1.5
3 picture1 picture555 picture255 picture365 picture112 1.5
4 picture1 picture555 picture255 picture365 picture112 1.5
有什么优雅的解决方案吗?
Is there any elegant solution?
推荐答案
print df.groupby('value')['tempx'].apply(' '.join).reset_index()
value tempx
0 1.5 picture1 picture555 picture255 picture365 pict...
这篇关于如何使用 pandas 将多行合并为单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文