Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataframe KeyError, although it exists

Given the data

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')

it works fine. However, this

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

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

like image 695
blue_note Avatar asked Jan 29 '19 13:01

blue_note


2 Answers

Add x to your columns:

df = pd.DataFrame.from_records(rows, index='x', columns=['x', 'y', 'z'])
like image 137
JE_Muc Avatar answered Sep 28 '22 18:09

JE_Muc


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
like image 41
gorjan Avatar answered Sep 28 '22 19:09

gorjan