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 进行分组,然后将它们重新连接在一起,但这似乎很麻烦,我想有更好的方法。