python - 列表的嵌套字典到数据框
问题描述
我有一本这样的字典:
{'a': {'col_1': [1, 2], 'col_2': ['a', 'b']},
'b': {'col_1': [3, 4], 'col_2': ['c', 'd']}}
当我尝试将其转换为数据框时,得到:
col_1 col_2
a [1, 2] [a, b]
b [3, 4] [c, d]
但我需要的是这个:
col_1 col_2
a 1 a
2 b
b 3 c
4 d
我怎样才能得到这种格式。也许我也应该改变我的输入格式?谢谢你的帮助=)
解决方案
您可以使用pd.DataFrame.from_dict
设置orient='index'
,以便将字典键设置为数据框的索引,然后通过应用展开所有列pd.Series.explode
:
pd.DataFrame.from_dict(d, orient='index').apply(pd.Series.explode)
col_1 col_2
a 1 a
a 2 b
b 3 c
b 4 d
推荐阅读
- c# - 应用程序在“Process.Start”之后在后台运行。如何解决这个问题?
- html - 如何在不偏移固定导航栏的情况下跳转到链接?
- django - Pipenv 无法在远程服务器上安装 boto3 (Heroku)
- r - dplyr 在变量的子集上使用 pivot_longer 和 pivot_wider
- php - phpseclib 绝对路径上传
- javascript - 如何在我的应用程序中提供用户对用户的付款?
- php - 单击提交按钮后找不到 $_FILES['uploadImg']['name']
- react-native - 在axios从api获取数据时实现ActivityIndicator
- python - 处理来自多个熊猫数据帧的数据时的插值方法?
- python - jQuery .show() 之后,Flask 页面继续执行 GET 请求