如何在大数据框中使用 GroupBy 连接字符串

How to Concatenate Strings from Using GroupBy in big data frames

我有这样一个数据框

import pandas as pd

#create DataFrame
df = pd.DataFrame({'store': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'quarter': [1, 1, 2, 2, 1, 1, 2, 2],
                   'employee': ['Andy', 'Bob', 'Chad', 'Diane',
                                'Elana', 'Frank', 'George', 'Hank']})

我想通过连接员工列中的值来减少重复行。我认为我能做到的唯一方法就是这样

#group by store and quarter, then concatenate employee strings
df.groupby(['store', 'quarter'], as_index=False).agg({'employee': ' '.join})

    store   quarter employee
0   A   1   Andy Bob
1   A   2   Chad Diane
2   B   1   Elana Frank
3   B   2   George Hank

这是一个最小的可重现数据,但我的真实数据框有很多列,我需要在 groupby 之后添加所有列名还是有其他方法可以做到这一点?

您也可以在不输入列名的情况下执行此操作。

下面以df为例:

In [1011]: df
Out[1011]: 
  store  quarter employee col1
0     A        1     Andy  abc
1     A        1      Bob  abc
2     A        2     Chad  abc
3     A        2    Diane  abc
4     B        1    Elana  abc
5     B        1    Frank  abc
6     B        2   George  abc
7     B        2     Hank  abc

使用:

In [1012]: df = df.groupby(['store', 'quarter'], as_index=False).agg(' '.join)

In [1013]: df
Out[1013]: 
  store  quarter     employee     col1
0     A        1     Andy Bob  abc abc
1     A        2   Chad Diane  abc abc
2     B        1  Elana Frank  abc abc
3     B        2  George Hank  abc abc

这将 运行 agg 在除 groupby 中提到的列之外的其余列上。

这会给你想要的答案

df = pd.DataFrame({'store': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'quarter': [1, 1, 2, 2, 1, 1, 2, 2],
                   'employee': ['Andy', 'Bob', 'Chad', 'Diane',
                                'Elana', 'Frank', 'George', 'Hank']})
df = df.groupby(['store', 'quarter'])['employee'].apply(list).agg(' '.join).reset_index(name='new')
df