Reputation: 341
I would like to create a dataframe with a dictionnary. I created my dictionnary, i would like convert this in Dataframe with one columns for the months and the second for value.
Do you have an idea for to resolve my problem ?
My dictionary : {'Jan': [1, 5], 'Apr': [2, 6], 'Mar': [3, 7], 'June': [4, 8]}
import pandas as pd
from collections import defaultdict
# d = {('20170330', 'A'): {'earn': '16.02'},('20170331', 'A'): {'earn': '25.68'},('20170330', 'AA'): {'earn': '321321'}}
months = ['Jan','Apr','Mar','June','Jan','Apr','Mar','June']
days = [1,2,3,4,5,6,7,8]
zipped = zip(months, days)
d = {}
for items in zipped:
res = d.setdefault(items[0], [])
res.append(items[1])
print(d)
Thnks you !
Upvotes: 1
Views: 43
Reputation: 93151
You can use stack
:
pd.DataFrame(d).stack() \
.rename_axis([None, 'Month']) \
.to_frame('Day') \
.reset_index(level=1) \
.reset_index(drop=True)
stack
produces a Series so the last 4 lines are just trying to produce a DataFrame and get it into shape.
Result:
Month Day
0 Jan 1
1 Apr 2
2 Mar 3
3 June 4
4 Jan 5
5 Apr 6
6 Mar 7
7 June 8
Upvotes: 1