【问题标题】:Using pandas groupby().apply(list) on multiple columns at once [duplicate]一次在多列上使用 pandas groupby().apply(list) [重复]
【发布时间】:2019-09-30 05:17:24
【问题描述】:

我正在尝试将数据框的多行合并为一行,并将具有不同值的列合并到一个列表中。有多个具有不同值的列。

df.groupby('a')['b'].apply(list) 如果只需要将 1 列(在本例中为“b”)添加到列表中,则效果很好,但我不知道如何为多列执行此操作。

数据框:

   a  b  c       d
0  1  b  1   first
1  1  b  2  second
2  2  c  1   third
3  2  c  2  fourth
4  2  c  3   fifth

首选数据帧发布操作:

   a  b          c                       d
0  1  b     [1, 2]         [first, second]
1  2  c  [1, 2, 3]  [third, fourth, fifth]

有没有简单的方法可以做到这一点?

【问题讨论】:

  • df.groupby(['a', 'b'])['c', 'd'].agg(list)
  • @Georgy:你甚至不需要指定column。是df.groupby(['a', 'b']).agg(list)

标签: python pandas dataframe apply pandas-groupby


【解决方案1】:
df = df.groupby(['a','b']).apply(lambda x: [list(x['c']), list(x['d'])]).apply(pd.Series)
df.columns =['a','b','c','d']

输出

   a  b          c                       d
0  1  b     [1, 2]         [first, second]
1  2  c  [1, 2, 3]  [third, fourth, fifth]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2019-08-07
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多