python - pandas 将相同的值合并在同一行中

标签 python python-3.x pandas dataframe pandas-groupby

有以下数据:

  board_href_deals       items  test1
0            test2  {'x': 'a'}  test1
1            test2  {'x': 'b'}  test2

对“board_href_deals”进行分组后, 我想以列表格式输出现有数据,如下所示:

 board_href_deals                     items     test1
0            test2  [{'x': 'a'}, {'x': 'b'}]    ['test1', 'test2']

谢谢

最佳答案

使用DataFrameGroupBy.agg ,在 pandas 0.23.4 中测试:

df = df.groupby('board_href_deals', as_index=False).agg(list)
print (df)
  board_href_deals                     items           test1
0            test2  [{'x': 'a'}, {'x': 'b'}]  [test1, test2]

谢谢@jpp 为老 Pandas 提供的解决方案:

df = df.groupby('board_href_deals').agg(lambda x: list(x))

关于python - pandas 将相同的值合并在同一行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075442/

相关文章:

python - 如何使用 python diff_match_patch 创建补丁并应用

python-3.x - OpenAI 耳语;找不到文件错误 : [WinError 2] The system cannot find the file specified

python - 如何使用 str.join() 而不是 "+="来加入带分隔符的字符串列表?

python - 如何根据集团内的实体找到最大金额?

python - 复制 pandas 列,根据之前的列给出值

python - 我需要用从该向量中获取的值来填充矩阵

python - re.sub() 具有具有副作用的替换功能

python - 什么是 R 的 qnorm() 的 Pandas 等价物

python - 使用 ajax 和 jquery 传递数据的简单 flask 应用程序服务器

python - 如何使用带有 pycurl 的 python 访问 Bugzilla 上错误的 XML 页面?