I have the following OrderedDict:
OrderedDict(
[
("2021-01-01" , {"name" : "John", "age" : 25}),
("2021-05-05" , {"name" : "Max", "age" : 15}),
("2021-09-09" , {"name" : "Michael", "age" : 35})
]
)
I need to convert it to a Pandas Dataframe where each key in each dict will be the column name, and dates will be the index of the DataFrame. How can I achieve this?
The expected result should like as the following:
where the date
column is the index of this DataFrame.
CodePudding user response:
We can get the expected result by using the transpose
method from Pandas :
>>> df = pd.DataFrame(data, columns=data.keys()).T
>>> df
name age
2021-01-01 John 25
2021-05-05 Max 15
2021-09-09 Michael 35
CodePudding user response:
Try with from_dict
out = pd.DataFrame.from_dict(d, 'index')
Out[484]:
name age
2021-01-01 John 25
2021-05-05 Max 15
2021-09-09 Michael 35
CodePudding user response:
I might have been beaten to the post here but here's the solution:
from collections import OrderedDict
x1 = OrderedDict(
[
("2021-01-01" , {"name" : "John", "age" : 25}),
("2021-05-05" , {"name" : "Max", "age" : 15}),
("2021-09-09" , {"name" : "Michael", "age" : 35})
]
)
pd.DataFrame.from_dict(x1).T.rename_axis('date').reset_index()