You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas聚合操作后无法找到Id列的问题排查与解决

解决Pandas聚合后Id列不存在的报错问题

问题出在你用groupby(df['Id'])完成聚合后,Id已经变成了DataFrame的索引,不再是普通列。所以打印时虽然能看到Id的值,但df_new.columns里不会包含它,直接筛选['Id', 'total1']自然会报错。

给你两种简单的解决办法:

方法1:聚合时让Id保持为列

修改groupby的代码,加上as_index=False参数,这样Id会保留成普通列,后续筛选就不会有问题:

import pandas as pd
  
# initialize list of lists
data = [['A29', 112, 10, 0.3], ['A29',112, 15, 0.1], ['A29', 112, 14, 0.22], ['A29', 88, 33, 0.09], ['A29', 88, 29, 0.1], ['A29', 88, 6, 0.2]]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Id', 'Cores', 'Provisioning', 'Utilization'])

df['total'] = df['Provisioning'] * df['Utilization']

df=df[['Id', 'Cores','total']]
aggregation_functions = {'Cores': 'first', 'total': 'sum'}
# 这里加上as_index=False,让Id保持为列
df_new = df.groupby('Id', as_index=False).aggregate(aggregation_functions)

df_new['total1']=df_new['total']/3
print(df_new)
print(df_new.columns) # 现在会包含Id列

df_new=df_new[['Id', 'total1']] # 正常运行不报错

方法2:聚合后把索引转成列

如果已经完成聚合操作,不想重新跑一遍,可以用reset_index()把索引转成普通列:

# 聚合后的原有代码之后
df_new = df_new.reset_index() # 把Id索引转为列
df_new=df_new[['Id', 'total1']] # 现在可以正常筛选

两种方法都能解决你的问题,推荐第一种,更直接高效。

内容的提问来源于stack exchange,提问作者ReactNewbie123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:02:13