尝试了一段时间,没有得到我想要的结果。
输入:
"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
关于python - 扩展字典数据框列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68065117/