python-3.x - Pandad - KeyError:列不在索引中
问题描述
我有一个熊猫数据框,其中包含 groupby 函数中的列列表。我收到一个错误
KeyError : "['Type1'] not in index"
下面给出的是引发错误的代码
temp_v1 = temp_df.groupby(level, as_index = False).sum()[[level, 'Type1', 'Type2','Type3', 'Type4', 'Type5']]
谁能指导我上面的数据框哪里出错了。谢谢..
解决方案
我猜问题是字符串列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']
推荐阅读
- python - 过滤后的 twitter api 流示例
- javascript - 像链接一样滑动
- php - PHP - 替换标签范围内的特定单词
- angular - 在谷歌应用引擎上部署带有环回的 Angular 10 应用
- python - 使用 Django 进行无效的 CSRF 验证
- c# - 我需要使用 Vector3.up、Vector3.down、ecc.将 Vector3 应用于 Vector3[] 但我不能
- ios - Swfit - 检查当前时间是否在两个时间字符串之间
- python - 具有特定半径的球体的 VTK/Paraview 可编程源
- sql - Oracle View 是否计算您不想查询的字段?
- mysql - 如何有效地对超过 10M 的记录进行分页