Pandas DataFrame选取索引列报错KeyError: 'customer' 求助
问题原因
你执行了df.set_index('customer'),这步操作把'customer'列设置成了DataFrame的索引,该列会从普通列列表中移除。后续操作完成后,最终的df里根本没有名为'customer'的列,所以用df['customer']访问会触发KeyError。
解决办法
根据你的需求,有两种处理方式:
1. 把'customer'恢复为普通列
修改代码,在数据计算完成后用reset_index()把索引转回普通列:
import pandas as pd df = pd.DataFrame({'customer' : ['customer2', 'customer1'], 'item1': [12, 13], 'item2' : [3, 28],'item3': [2, 1]}) df2 = pd.DataFrame({'customer' : ['customer1', 'customer2'], 'item?': ['item1', 'item1'], 'quantity' : [2, 5]}) # 先完成数据计算,得到以customer为索引的结果 df_processed = df.set_index('customer').add(pd.pivot_table(df2,index='customer',columns='item?',values='quantity')).fillna(df.set_index('customer')).astype(int) # 将索引转回普通列 df = df_processed.reset_index() print(df['customer'])
2. 直接访问索引(无需转成列)
如果只是需要获取'customer'对应的取值,直接访问索引即可:
# 打印索引的所有值 print(df.index) # 或者打印成数组形式 print(df.index.values)
内容的提问来源于stack exchange,提问作者kucb
相关产品推荐
相关产品推荐

