【问题标题】:Pandas dataframe grouping values熊猫数据框分组值
【发布时间】:2017-09-06 13:57:41
【问题描述】:

我有一个这样的熊猫数据框,

dd = pd.DataFrame(
{'name': ['abc','bcd','abc'],
 'seconds': [75,77,90],
})

我需要将 seconds 列合并到一个列表中以显示具有相同名称的行。

我可以使用 for 循环来做到这一点,

names= list(set(dd['name']))
counter=[]
for a in names:
    counter.append(list(dd[dd['name'] == a]['seconds']))
end
seconds_list = pd.DataFrame(
{'name': names,
'seconds': counter,
})

输出:

但这需要大量时间在大数据帧上。有什么简单的方法可以在没有 for 循环的情况下实现这一点?

谢谢!

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    使用groupbyapply list

    df = dd.groupby('name')['seconds'].apply(list).reset_index()
    print (df)
    
      name   seconds
    0  abc  [75, 90]
    1  bcd      [77]
    

    【讨论】:

      【解决方案2】:

      使用groupbyaggtolist

       dd.groupby('name')['seconds'].agg(lambda x: x.tolist()).reset_index(name='seconds')
      

      输出:

        name   seconds
      0  abc  [75, 90]
      1  bcd      [77]
      

      【讨论】:

        猜你喜欢
        • 2017-10-17
        • 2019-05-03
        • 2022-01-12
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        相关资源
        最近更新 更多