首页 > 解决方案 > 扩展字典数据框列表

问题描述

尝试了一段时间,无法得到我想要的结果。

输入:

"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 但无法正常工作。

任何帮助将不胜感激!

谢谢!

标签: pythonpandasdataframe

解决方案


这是另一个解决方案:

#!/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_normalisehttps ://towardsdatascience.com/all-pandas-json-normalize-you-should-know-for-flattening-json-13eae1dfb7dd


推荐阅读