【问题标题】:pandas Consolidate same values in the same rowpandas 在同一行合并相同的值
【发布时间】:2018-08-29 10:40:32
【问题描述】:

有以下数据:

  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']

谢谢

【问题讨论】:

  • df.groupby('board_href_deals').agg(list) 工作怎么样?

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


【解决方案1】:

使用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 为老熊猫提供解决方案:

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

【讨论】:

    【解决方案2】:

    另一种解决方案,尤其是在旧版本的 Pandas 上,是在一个序列上使用GroupBy + apply,然后通过concat 组合。

    在 Python 3.60 / Pandas 0.19.2 上进行基准测试。这个人为的例子有少量的组;如果效率是一个问题,你应该用你的数据进行测试。

    import pandas as pd
    
    df = pd.DataFrame({'A': ['test2', 'test2', 'test4', 'test4'],
                       'B': [{'x': 'a'}, {'x': 'b'}, {'y': 'a'}, {'y': 'b'}],
                       'C': ['test1', 'test2', 'test3', 'test4']})
    
    df = pd.concat([df]*10000)
    
    def jpp(df):
        g = df.groupby('A')
        L = [g[col].apply(list) for col in ['B', 'C']]
        return pd.concat(L, axis=1).reset_index()
    
    %timeit jpp(df)                                 # 11.3 ms per loop
    %timeit df.groupby('A').agg(lambda x: list(x))  # 20.5 ms per loop
    

    【讨论】:

    • 小心,只有4个大组,所以比较快。我认为在更多组中,您的解决方案应该更慢。
    • @jezrael,是的,用户应该一如既往地测试他们的数据。 可能会更好,具体取决于 # 个组与每组项目的比例。
    • 我会添加评论。我们没有足够的数据来做出一种或另一种判断。最好展示所有解决方案:)
    • 当然,所以如果为更多组添加解决方案,它应该真的很好;)
    • @jezrael,不同意,这没有必要。不同的解决方案可以满足不同的边缘情况。这是 SO 的常见做法。这也是我们在问题得到回答后不关闭的原因之一!
    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多