python - 扩展字典数据框列表
问题描述
尝试了一段时间,无法得到我想要的结果。
输入:
"cursor":"YXJyYXljb25uZWN0aW9uOjA=",
"node":{
"class":1,
"end": [
{"part": "a", "see" : "c"},
{"part": "b", "see" : "c"}
]
}
DF 中的所需输出。
cursor class end.part end.see
YXJyYXljb25uZWN0aW9uOjA 1 a c
YXJyYXljb25uZWN0aW9uOjA 1 b c
我尝试使用 json_normalise 但无法正常工作。
任何帮助将不胜感激!
谢谢!
解决方案
这是另一个解决方案:
#!/usr/bin/python3
import pandas as pd
dic = {
"cursor":"YXJyYXljb25uZWN0aW9uOjA=",
"node":{
"class":1,
"end": [
{"part": "a", "see" : "c"},
{"part": "b", "see" : "c"}
]
}
}
# 1. Use `meta` to specify what we want to show in the result
# 2. Use 'record_path` to flatten the nested list
df = pd.json_normalize(dic, meta=['cursor', ['node', 'class']],
record_path=['node', 'end'] , record_prefix='end.')
# Rename the 'node.class' column to 'class'
df = df.rename(columns={'node.class': 'class'})
# Reindex by the order of columns list
df = df.reindex(columns=['cursor', 'class', 'end.part', 'end.see'])
print(df)
参考pd.json_normalise
:https ://towardsdatascience.com/all-pandas-json-normalize-you-should-know-for-flattening-json-13eae1dfb7dd
推荐阅读
- cassandra - Kafka Connect Sink 到 Cassandra :: java.lang.VerifyError: Bad return type
- python-3.x - (无法将字符串转换为浮点数)使用 knn 算法时出错
- c++ - 当指向删除和指向不同的对象时,C++ 中的 Seg 错误指针
- c++ - Graphviz 作为 Windows 中的库
- java - 如何在 Spring 中使用 CommandLineRunner 测试 JPA 实体?
- javascript - 如何使用 VIDEO 作为置换贴图修改 PIXI.js 中的置换贴图参数?
- python - 对包含数字的列表进行排序:
- mouseevent - 为什么在 p5.js 中没有 setup() 时 mousePressed() 不能工作?
- jboss-developer-studio - 无法在 Eclipse 中下载 Red Hat CodeReady Studio
- c# - 如何从实体框架锁定在编辑模式下重复出现