Python 如何使用熊猫将多行合并为一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36392735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:49:27  来源:igfitidea点击:

How to combine multiple rows into a single row with pandas

pythonpandas

提问by Sandeep Raikar

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

I want the dataframe to be converted like this: (space separated) tempx values

我希望像这样转换数据帧:(空格分隔)tempx 值

  Expected output:
  tempx                                                       value
  0     picture1 picture555 picture255 picture365 picture112  1.5

  or
  as a python dict
  {1.5:{picture1 picture555 picture255 picture365 picture112}}

What I have tried :

我尝试过的:

 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?

有什么优雅的解决方案吗?

回答by jezrael

You can use groupbyand applyfunction join:

您可以使用groupbyapply功能join

print df.groupby('value')['tempx'].apply(' '.join).reset_index()
   value                                              tempx
0    1.5  picture1 picture555 picture255 picture365 pict...