dataframe KeyError,虽然它存在

blu*_*ote 3 python dataframe pandas

鉴于数据

rows = [
    {'x': 1, 'y': 2, 'z': 3},
    {'x': 2, 'y': 2, 'z': 3},
]
Run Code Online (Sandbox Code Playgroud)

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

frame = pd.DataFrame.from_records(rows, index='x')
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是,这个

frame = pd.DataFrame.from_records(rows, index='x', columns=['y', 'z'])
Run Code Online (Sandbox Code Playgroud)

(我希望它是等价的)因奇怪的错误而失败:KeyError: 'x'.怎么了?

Sco*_*y1- 5

添加x到您的columns:

df = pd.DataFrame.from_records(rows, index='x', columns=['x', 'y', 'z'])
Run Code Online (Sandbox Code Playgroud)


gor*_*jan 3

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

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
Run Code Online (Sandbox Code Playgroud)