首页 > 解决方案 > Pandad - KeyError:列不在索引中

问题描述

我有一个熊猫数据框,其中包含 groupby 函数中的列列表。我收到一个错误

KeyError : "['Type1'] not in index"

下面给出的是引发错误的代码

temp_v1 = temp_df.groupby(level, as_index = False).sum()[[level, 'Type1', 'Type2','Type3', 'Type4', 'Type5']]

谁能指导我上面的数据框哪里出错了。谢谢..

标签: python-3.xpandaspandas-groupby

解决方案


我猜问题是字符串列Type1

level = 'F'
temp_df = pd.DataFrame({
         'Type1':list('abcdef'),
         'Type2':[4,5,4,5,5,4],
         'Type3':[7,8,9,4,2,3],
         'Type4':[1,3,5,7,1,0],
         'Type5':[5,3,6,9,2,4],
         'col':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

print (temp_df.dtypes)
Type1    object
Type2     int64
Type3     int64
Type4     int64
Type5     int64
col       int64
F        object
dtype: object

解决方案是在函数之前添加列表sum,但Type1被排除,因为不是 numeric

cols = [level, 'Type1', 'Type2','Type3', 'Type4', 'Type5']
temp_v1 = temp_df.groupby(level, as_index = False)[cols].sum()
print (temp_v1)
   F  Type2  Type3  Type4  Type5
0  a     13     24      9     14
1  b     14      9      8     15

另一个问题是列名中的拼写错误或空格,您可以通过将列名转换为list

print (temp_df.columns.tolist())
['Type1', 'Type2', 'Type3', 'Type4', 'Type5', 'col', 'F']

推荐阅读