This question is similar to Pandas DataFrame to List of Dictionaries, except that the DataFrame
is not 'full': there are some nan
values in it. Suppose I generate a DataFrame
from a list of dictionaries like so:
import pandas as pd
data = [{'foo': 1, 'bar': 2}, {'foo': 3}]
df = pd.DataFrame(data)
so that the resulting df
looks like
bar foo
0 2.0 1
1 NaN 3
I would like a function which turns df
back into the original data
list of dictionaries. Unfortunately,
assert df.to_dict('records') == data
fails because the former is
[{'bar': 2.0, 'foo': 1.0}, {'bar': nan, 'foo': 3.0}]
with the additional 'bar': nan
key-value pair in the second item. How can I get back the original data
?