在 groupby agg 中使用列名列表?

2023-12-22

Summary:

我有许多带有数据(data_cols)和文本(text_cols)的列,我想通过引用列名列表来执行以下操作,但无法弄清楚:df.groupby('id', as_index=False).agg({data_cols: 'sum', text_cols: 'first'})

解释:

我有一个包含约 30 列的数据框,其中一些列包含值,其他列包含文本。我想对具有相同 id 的所有值进行求和,并让文本使用第一个条目。我可以通过使用 groupby 来实现这一点:

d = {'id': ['a', 'a', 'b', 'c'], 'value1': [1, 2, 3, 4], 'value2': [5, 6, 7, 8], 'text1': ['w', 'x', 'y', 'z']}
df = pd.DataFrame(d)

  id  value1  value2 text1
0  a       1       5     w
1  a       2       6     x
2  b       3       7     y
3  c       4       8     z

df.groupby('id', as_index=False).agg({'value1': 'sum', 'value2': 'sum', 'text1': 'first'})

  id  value1  value2 text1
0  a       3      11     w
1  b       3       7     y
2  c       4       8     z

这正是我想要实现的目标,只是我有很多列并且不希望写出所有列名称。因此,我尝试了不同的方法来引用多个列,但没有任何效果。

data_cols = df.columns[1:3]
text_cols = set(df.columns) - set(data_cols)

df.groupby('id', as_index=False).agg({data_cols: 'sum', text_cols: 'first'})

在这里,我得到TypeError: unhashable type: 'Index',所以我想我可以通过使用来避免这种情况tuple:

data_cols = tuple(df.columns[1:3])
text_cols = tuple(set(df.columns) - set(data_cols)) #I have many data columns and some text columbs before and after them

这给了我:SpecificationError: Column(s) [('text1', 'id'), ('value1', 'value2')] do not exist我认为它的观点('value1', 'value2')作为单个列,而不是将其解压缩为两列。有什么方法或格式可以避免这种情况吗?

或者,我可以将 df 分成 2 个 df:df_values 和 df_text,对 df_values 进行分组,然后将它们重新连接在一起,但这似乎很麻烦,我想有更好的方法。


创建字典通过dict.fromkeys并合并它们,最后传递到agg:

data_cols = df.columns[1:3]
text_cols = set(df.columns) - set(data_cols)
d1 = dict.fromkeys(data_cols, 'sum')
d2 = dict.fromkeys(text_cols, 'first')

#https://stackoverflow.com/questions/38987
d = {**d1, **d2}

df.groupby('id', as_index=False).agg(d)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 groupby agg 中使用列名列表? 的相关文章

随机推荐