I have a list of dicts where each dict can have different keys. I want to create a dataframe with one row where each key is a column and the row is its value:
import pandas as pd
data = [{"A":1}, {"B":2}, {"C":3}]
df = pd.DataFrame(data)
print(df.to_string(index=False))
# A B C
# 1.0 NaN NaN
# NaN 2.0 NaN
# NaN NaN 3.0
What I want:
# A B C
# 1.0 2.0 3.0
How can I drop/compact the rows with NaN values?
You can flatten dictionaries and create DataFrame by constructor:
from collections import ChainMap
df = pd.DataFrame([ChainMap(*data)])
print (df)
A B C
0 1 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