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?
Add x
to your columns
:
df = pd.DataFrame.from_records(rows, index='x', columns=['x', 'y', 'z'])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With