如何结合列索引与列名使用Pandas的groupby方法?
问题:结合列位置与列名执行groupby操作的实现方法
我正在编写一个函数,使用groupby对多个DataFrame进行筛选。示例DataFrame如下,但每个DataFrame的列数并不固定:
df = pd.DataFrame({ 'xyz CODE': [1,2,3,3,4, 5,6,7,7,8], 'a': [4, 5, 3, 1, 2, 20, 10, 40, 50, 30], 'b': [20, 10, 40, 50, 30, 4, 5, 3, 1, 2], 'c': [25, 20, 5, 15, 10, 25, 20, 5, 15, 10] })
每个DataFrame的首列名称各不相同,但其余列名称在所有DataFrame中保持一致。我想知道:能否结合列位置与列名执行groupby操作?具体该如何实现?
我编写了如下函数,但出现报错TypeError: unhashable type: 'list':
def filter_all_df(df): df['max_c'] = df.groupby(df.columns[0])['a'].transform('max') newdf = df[df['a'] == df['max_c']].drop(['max_c'], axis=1) newdf['max_score'] = newdf.groupby([newdf.columns[0],'a','b'])['c'].transform('max') newdf = newdf[newdf['c'] == newdf['max_score']] newdf = newdf.sort_values([newdf.columns[0]]).drop_duplicates([newdf.columns[0], 'a','b', 'c'], keep='last') newdf.to_csv('newdf_all.csv') return newdf
解决方案
完全可以结合列位置与列名执行groupby操作,核心是通过列位置提取对应的列名字符串,再和其他列名配合使用。你的报错大概率是代码重复调用df.columns[0]导致的潜在问题,或是首列包含不可哈希的元素(比如列表类型的值)。下面是修正后的代码,同时优化了可读性:
def filter_all_df(df): # 提取首列的列名,用变量存储避免重复调用 key_col = df.columns[0] # 按首列分组,标记每个组内a列的最大值 df['max_c'] = df.groupby(key_col)['a'].transform('max') newdf = df[df['a'] == df['max_c']].drop(['max_c'], axis=1) # 按首列、a、b列分组,标记每个组内c列的最大值 newdf['max_score'] = newdf.groupby([key_col, 'a', 'b'])['c'].transform('max') newdf = newdf[newdf['c'] == newdf['max_score']].drop(['max_score'], axis=1) # 按首列排序并去重 newdf = newdf.sort_values(key_col).drop_duplicates([key_col, 'a', 'b', 'c'], keep='last') newdf.to_csv('newdf_all.csv') return newdf
关键说明:
- 先通过
df.columns[0]获取首列的列名字符串,存入变量key_col,后续直接使用该变量,既清晰又避免重复解析列名的潜在问题。 - 在
groupby中,将key_col与固定列名(如'a'、'b')放在同一个列表里,就能实现结合列位置与列名的分组操作。 - 如果仍出现
unhashable type: 'list'报错,检查首列的元素类型:如果首列存在列表、字典这类不可哈希的值,需要先将其转为可哈希类型(比如把列表转成元组),才能正常执行groupby。
用你的示例DataFrame测试,运行上述函数后会得到符合预期的筛选结果:
xyz CODE a b c 0 1 4 20 25 1 2 5 10 20 3 3 1 50 15 4 4 2 30 10 5 5 20 4 25 6 6 10 5 20 8 7 50 1 15 9 8 30 2 10
内容的提问来源于stack exchange,提问作者byc
相关产品推荐
相关产品推荐

