python - 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
解决方案
使用带有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
推荐阅读
- cassandra - 尝试从 Python 代码中检索 CassandraDB 记录时收到以下警告
- java - 用 sqlite 同步改造
- java - 无法启动活动 ComponentInfo - android.view.InflateException - android.support.v7.widget.RecyclerView
- java - Google Guice + TestNG(v6.14.3) 组抛出 java.lang.RuntimeException:无法实例化资源
- maven - 包 org.assertj.core.api 不存在
- python - CNN 与 keras 预测能量
- php - 在自定义模块中加载外部 JS
- amazon-web-services - 如何将 python 本地项目安装到 lambci/lambda docker 映像中?
- html - 我怎样才能更简单地写这个?这是 HTML.jason 狙击手
- java - 在 tomcat 上运行 springMVC 项目,但我必须每个月重新启动 Web 服务器。我应该怎么办?