python - 扩展字典数据框列表

标签 python pandas dataframe

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

输入:

"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/

相关文章:

python - pip install -U 中的 "-U"选项代表什么

python - 使用 Python Paramiko 将 .csv 文件从 SFTP 服务器读取到内存

python - Groupby 客户和商店 - 获得平均交易频率。日期问题

python - Numpy:比较两个数据集的适应性

python - 当包含 NaN 时使用 "new information"更新 Pandas 数据帧

python - 根据另一个数据框中的数据量删除数据框中的行

python - 为 pandas DataFrame 滚动 idxmin/max

python pandas将数据框列拆分为两个新列并删除原始列

python - 使用 Scikit-learn (sklearn) 估算整个 DataFrame(所有列)而不迭代列

Python Tk Canvas 项事件绑定(bind): iterating bindings over multiple items