首页 > 解决方案 > Python: Dictionary to pandas dataframe

问题描述

I would like to change the dictionary to pandas dataframe.

data = {u'Diluted Normalized EPS': [{u'date': u'2020-01-03', u'value': u'-0.446810'}, {u'date': u'2019-10-04', u'value': u'-0.765540'}, {u'date': u'2019-06-28', u'value': u
'-0.574240'}, {u'date': u'2019-03-29', u'value': u'-2.063700'}, {u'date': u'2018-12-28', u'value': u'-0.841380'}], u'Net Income Before Extra. Items': [{u'date': u'2020-01-03', u'value': u'-139.000000'}, {u'date': u'2019-10-04', u'value': u'-276.000000'}, {u'date': u'2019-06-28', u'value': u'-185.000000'}, {u'date': u'2019-03-29', u'value': u'-652.000000'}, {u'date': u'2018-12-28', u'value': u'-257.000000'}]}

I would like to convert to Pandas dataframe as below

         date  Diluted Normalized EPS  Net Income Before Extra. Items
0  2020-01-03  -0.446810                -139.000000
1  2019-10-04  -0.765540                -276.000000
2  2019-06-28  -0.574240                -185.000000
3  2019-03-29  -2.063700                -652.000000
4  2018-12-28  -0.841380                -257.000000

pd.DataFrame(data) unable to return the desired results

标签: pythonpandasdictionary

解决方案


使用带有DataFrame构造函数的嵌套字典理解:

d = {k:{x['date']: x['value'] for x in v} for k, v in data.items()}
df = pd.DataFrame(d).rename_axis('date').reset_index()
print(df)
         date Diluted Normalized EPS Net Income Before Extra. Items
0  2020-01-03              -0.446810                    -139.000000
1  2019-10-04              -0.765540                    -276.000000
2  2019-06-28              -0.574240                    -185.000000
3  2019-03-29              -2.063700                    -652.000000
4  2018-12-28              -0.841380                    -257.000000

推荐阅读