数据框KeyError,尽管存在 [英] dataframe KeyError, although it exists

查看:69
本文介绍了数据框KeyError,尽管存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供数据

rows = [
    {'x': 1, 'y': 2, 'z': 3},
    {'x': 2, 'y': 2, 'z': 3},
]

如果我尝试构建这样的数据框

if I try constructing a dataframe like this

frame = pd.DataFrame.from_records(rows, index='x')

它工作正常.但是,这

frame = pd.DataFrame.from_records(rows, index='x', columns=['y', 'z'])

(我希望它是等效的)失败,并出现奇怪的错误:KeyError: 'x'.怎么了?

(which I would expect to be equivalent) fails with the weird error: KeyError: 'x'. What's wrong?

推荐答案

您需要在列中包含x.例如:

You need to include x in you columns. Eg:

rows = [{'x': 1, 'y': 2, 'z': 3}, {'x': 2, 'y': 2, 'z': 3}]
frame = pd.DataFrame.from_records(rows, index='x')
display(frame)
    y   z
x       
1   2   3
2   2   3
frame = pd.DataFrame.from_records(rows, index='x', columns=['x', 'y', 'z'])
display(frame)
    y   z
x       
1   2   3
2   2   3

这篇关于数据框KeyError,尽管存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆