python - 如何将带有字典列的数据框转换为多级数据框
问题描述
我有 DataFrame,其中包含列中的字典。
可以如下创建
lis = [
{'id': '1',
'author': {'self': 'A',
'displayName': 'A'},
'created': '2018-12-18',
'items': {'field': 'status',
'fromString': 'Backlog'}},
{'id': '2',
'author': {'self': 'B',
'displayName': 'B'},
'created': '2018-12-18',
'items': {'field': 'status',
'fromString': 'Funnel'}}]
pd.DataFrame(lis)
author created id items
0 {'self': 'A', 'displayName': 'A'} 2018-12-18 1 {'field': 'status', 'fromString': 'Backlog'}
1 {'self': 'B', 'displayName': 'B'} 2018-12-18 2 {'field': 'status', 'fromString': 'Funnel'}
我想将此信息转换为多级 DataFrame。
我一直在尝试
pd.MultiIndex.from_product(lis)
pd.MultiIndex.from_frame(pd.DataFrame(lis))
但无法得到我正在寻找的结果。基本上我想要如下:
author created id items
self displayName field fromString
A A 2018-12-18 1 status Backlog
B B 2018-12-18 2 status Funnel
关于我如何实现这一目标的任何建议?
谢谢
解决方案
您可以使用json.json_normalize
- 但列名称用.
分隔符展平:
from pandas.io.json import json_normalize
lis = [
{'id': '1',
'author': {'self': 'A',
'displayName': 'A'},
'created': '2018-12-18',
'items': {'field': 'status',
'fromString': 'Backlog'}},
{'id': '2',
'author': {'self': 'B',
'displayName': 'B'},
'created': '2018-12-18',
'items': {'field': 'status',
'fromString': 'Funnel'}}]
df = json_normalize(lis)
print (df)
id created author.self author.displayName items.field items.fromString
0 1 2018-12-18 A A status Backlog
1 2 2018-12-18 B B status Funnel
对于MulitIndex
in columns 和 in index - 首先Mulitiindex
由所有没有.
by的列创建DataFrame.set_index
,然后使用str.split
:
df = df.set_index(['id','created'])
df.columns = df.columns.str.split('.', expand=True)
print (df)
author items
self displayName field fromString
id created
1 2018-12-18 A A status Backlog
2 2018-12-18 B B status Funnel
如果MulitIndex
在列中需要 - 有可能,但会在列名中获取缺失值:
df.columns = df.columns.str.split('.', expand=True)
print (df)
id created author items
NaN NaN self displayName field fromString
0 1 2018-12-18 A A status Backlog
1 2 2018-12-18 B B status Funnel
缺失值应替换为空字符串:
df = df.rename(columns= lambda x: '' if x != x else x)
print (df)
id created author items
self displayName field fromString
0 1 2018-12-18 A A status Backlog
1 2 2018-12-18 B B status Funnel
推荐阅读
- jquery - 如何将所有图像向左滑动
- android - 使用 Gradle 插件 3.6.2 的调试应用程序版本缺少 classes.jar
- .net - .NET 表格;如何从应用程序访问已安装的包?
- python - 将注释从 Mask-RCNN 数据集格式转换为 COCO 格式
- java - 在地图中执行 removeAt 时出现 ArrayIndexOutOfBoundsException
- spring - Spring Boot Security ,基于表单的登录以调用自定义 API 进行身份验证
- laravel - Laravel:HasManyThrough 多态问题
- android - Gradle 给我写 AAPT 错误
- docker - windows docker桌面kubernetes中的错误
- python - NiFi 的 ScriptedReader 的 Python 示例