Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merging two dictionaries as rows into one pandas dataframe

My question is similar to

Merging two dictionaries into one dataframe

but that question asked how to merge two dictionaries in one dataframe, using the dictionaries as columns. In my case, the dictionaries are the rows of the dataframe. MRE:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foo = {‘mean’: 0.11, ‘median’: 0.09, ‘p90’: 0.24}
bar = {‘mean’: 0.10, ‘median’: 0.09, ‘p90’: 0.20}

I want a dataframe like this:

set mean median  p90
foo 0.11   0.09 0.24
bar 0.10   0.09 0.20

how can I create it?

>Solution :

Let us do

d = {'foo': foo, 'bar': bar}
pd.DataFrame(d).T.rename_axis('set').reset_index()

Alternative approach with comprehension

d = {'foo': foo, 'bar': bar}
pd.DataFrame({'set': k, **v} for k, v in d.items())

   set  mean  median   p90
0  foo  0.11    0.09  0.24
1  bar  0.10    0.09  0.20
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading