Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas compact rows when data is missing

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?

like image 434
BERA Avatar asked Dec 08 '25 08:12

BERA


1 Answers

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
like image 166
jezrael Avatar answered Dec 09 '25 21:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!