Pandas 按多列对dataframe进行分组,并将结果附加到dataframe

Pandas 按多列对dataframe进行分组,并将结果附加到dataframe,pandas,pandas-groupby,Pandas,Pandas Groupby,然而,这类似于,当在pandas v0.14中按多个列进行分组时,该解决方案不起作用 例如: $ df = pd.DataFrame([ [1, 1, 1], [1, 2, 1], [1, 2, 2], [1, 3, 1], [2, 1, 1]], columns=['id', 'country', 'source']) 以下计算工作: $ df.groupby(['id','country'])['source'].apply(lambda x

然而,这类似于,当在pandas v0.14中按多个列进行分组时,该解决方案不起作用

例如:

$ df = pd.DataFrame([
    [1, 1, 1],
    [1, 2, 1],
    [1, 2, 2],
    [1, 3, 1],
    [2, 1, 1]],
    columns=['id', 'country', 'source'])
以下计算工作:

$ df.groupby(['id','country'])['source'].apply(lambda x: x.unique().tolist())


0       [1]
1    [1, 2]
2    [1, 2]
3       [1]
4       [1]
Name: source, dtype: object
但将输出分配给新列会导致错误:

df['source_list'] = df.groupby(['id','country'])['source'].apply(
                               lambda x: x.unique().tolist())
TypeError:插入列的索引与框架索引不兼容


将分组结果与初始数据帧合并:

>>> df1 = df.groupby(['id','country'])['source'].apply(
             lambda x: x.tolist()).reset_index()

>>> df1
  id  country      source
0  1        1       [1.0]
1  1        2  [1.0, 2.0]
2  1        3       [1.0]
3  2        1       [1.0]

>>> df2 = df[['id', 'country']]
>>> df2
  id  country
1  1        1
2  1        2
3  1        2
4  1        3
5  2        1

>>> pd.merge(df1, df2, on=['id', 'country'])
  id  country      source
0  1        1       [1.0]
1  1        2  [1.0, 2.0]
2  1        2  [1.0, 2.0]
3  1        3       [1.0]
4  2        1       [1.0]

通过将
groupby.apply的结果重新分配给原始数据帧,可以在不进行合并的情况下实现这一点

df = df.groupby(['id', 'country']).apply(lambda group: _add_sourcelist_col(group))
当您的
\u add\u sourcelist\u col
函数

def _add_sourcelist_col(group):
    group['source_list'] = list(set(group.tolist()))
    return group
请注意,还可以在定义的函数中添加其他列。只需将它们添加到每个组数据帧中,并确保在函数声明的末尾返回组

编辑:我会留下上面的信息,因为它可能仍然有用,但我误解了原始问题的一部分。OP想要实现的目标可以通过

df = df.groupby(['id', 'country']).apply(lambda x: addsource(x))

def addsource(x):
    x['source_list'] = list(set(x.source.tolist()))
    return x

避免事后合并的另一种方法是在应用于每个组的函数中提供索引,例如

def calculate_on_group(x):
    fill_val = x.unique().tolist()
    return pd.Series([fill_val] * x.size, index=x.index)

df['source_list'] = df.groupby(['id','country'])['source'].apply(calculate_on_group)