Simon Lindgren
Simon Lindgren

Reputation: 2031

Merging two dictionaries into one dataframe

These are two dictionaries:

monkeydict = {'16:43': 1, '16:44': 1, '16:49': 3}
pigdict = {'16:41': 3, '16:44': 2, '16:51': 3}

This is the desired dataframe:

time,monkeydict,pigdict
16:41,,3
16:43,1,
16:44,1,2
16:49,3,
16:51,,3

Upvotes: 12

Views: 15750

Answers (2)

BENY
BENY

Reputation: 323226

pd.DataFrame({'monkeydict':pd.Series(monkeydict),'pigdict':pd.Series(pigdict)})
Out[879]: 
       monkeydict  pigdict
16:41         NaN      3.0
16:43         1.0      NaN
16:44         1.0      2.0
16:49         3.0      NaN
16:51         NaN      3.0

Or (Notice here, you need to rename your columns after create the data frame)

pd.DataFrame([monkeydict,pigdict]).T
Out[887]: 
         0    1
16:41  NaN  3.0
16:43  1.0  NaN
16:44  1.0  2.0
16:49  3.0  NaN
16:51  NaN  3.0

Upvotes: 15

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

In [9]: (pd.Series(monkeydict).to_frame('monkey')
           .join(pd.Series(pigdict).to_frame('pig'), how='outer'))
Out[9]:
       monkey  pig
16:41     NaN  3.0
16:43     1.0  NaN
16:44     1.0  2.0
16:49     3.0  NaN
16:51     NaN  3.0

Upvotes: 4

Related Questions