python - 将嵌套字典解包到 pandas DataFrame
问题描述
我的字典目前是这样设置的:
{'0001': {'Batting Hours': [79, 154, 50, 172],
'Bowling Hours': [101, 82, 298],
'Date': ['02/02/2019', '02/01/2019', '02/04/2019', '02/03/2019']},
'0002': {'Batting Hours': [7, 23, 40],
'Bowling Hours': [14, 30, 43],
'Date': ['02/04/2019', '02/01/2019', '02/02/2019']}}
我如何解开这个字典,以便数据框有这样的输出:
Code Date Batting Hours Bowling Hours
0001 02/02/2019 79 101
0001 02/01/2019 154 82
我尝试查看有关其他类似数据结构如何展开的文档,但我似乎无法理解。
我目前正在将这些值附加到这样的列表中
player_agg_hours_dict[Player]['Batting Hours'].append(aggregate_batting_hours)
我正在尝试输出到这样的数据框:
output_df = pd.DataFrame.from_dict(player_agg_hours_dict, orient='index').transpose() # convert dict to dataframe
而且我知道from_dict()
参数必须有所不同。
解决方案
一种方法是使用stack
和的组合unstack
:
v = pd.DataFrame(dct).stack()
(pd.DataFrame(v.tolist(), index=v.index)
.stack()
.unstack(0)
.reset_index(level=1, drop=True)
.rename_axis('Code')
.reset_index())
Code Batting Hours Bowling Hours Date
0 0001 79 101 02/02/2019
1 0001 154 82 02/01/2019
2 0001 50 298 02/04/2019
3 0001 172 NaN 02/03/2019
4 0002 7 14 02/04/2019
5 0002 23 30 02/01/2019
6 0002 40 43 02/02/2019
您也可以从以下步骤开始concat
:
(pd.concat({k: pd.DataFrame.from_dict(v, orient='index') for k,v in dct.items()})
.stack()
.unstack(1)
.reset_index(level=1, drop=True)
.rename_axis('Code')
.reset_index())
Code Date Batting Hours Bowling Hours
0 0001 02/02/2019 79 101
1 0001 02/01/2019 154 82
2 0001 02/04/2019 50 298
3 0001 02/03/2019 172 NaN
4 0002 02/04/2019 7 14
5 0002 02/01/2019 23 30
6 0002 02/02/2019 40 43
推荐阅读
- ionic-framework - Ionic 3:内联显示离子搜索栏和离子段按钮
- laravel - Laravel MethodNotAllowedHttpException 如果请求具有 base64 图像数据
- unity3d - 着色器 - 将 PerRendererData 与数组属性一起使用
- jena - 在开发基于知识的 QA 系统时,何时需要使用像 jena 这样的推理器?
- mule-esb - Mule 中的 Http 处理程序
- java - 如何在同一线程上暂停系统
- vhdl - 将 DHT22 连接到 FPGA - elbert v2
- scala - 如何在子类的 scaladocs 中覆盖 @define
- c - Raspberry:通过 DMA 的 PWM 是如何工作的?
- ios - 应用程序被杀死时点击推送通知后应用程序崩溃