首页 > 解决方案 > 如何在流数据中将复杂字典创建到 Pandas DataFrame 中

问题描述

各种嵌套字典和数据结构:)

我有一个样本字典 -

stream= {
    "Outerclass": {
        "Main_ID": "1",
        "SetID": "1041",
        "Version": 2,
        "nestedData": {
            "time": ["5000", "6000", "7000"],
            "value": [1, 2, 3]
        }

    } }

我想像这样创建一个数据框 -

  Main_ID SetID  Version  Time  Value
0     1     1041      2.0  5000      1
1     1     1041      2.0  6000      2
2     1     1041      2.0  7000      3

我已经编写了下面的代码来产生我需要的东西,我知道这不是一个好方法,如果有人可以帮助建议那将是很棒的。此外,我确信当我针对流数据运行它时,它的表现会很糟糕。这 3 个数据帧将在一个循环中创建,数据范围可以从 30,000 到 1,00,000 的时间和值列表。

代码-

import pandas as pd

stream =  {
    "Outerclass": {
        "Main_ID": "1",
        "SetID": "1041",
        "Version": 2,
        "nestedData": {
            "time": ["5000", "6000", "7000"],
            "value": [1, 2, 3]
        }

    } }

df_outer = pd.DataFrame(stream["Outerclass"], index=[0])
print(df_outer)


df_time = pd.DataFrame(stream["Outerclass"]["nestedData"]["time"], columns=["Time"])
print(df_time)

df_value = pd.DataFrame(stream["Outerclass"]["nestedData"]["value"], columns=["Value"])
print(df_value)

full_df = pd.concat([df_outer,df_time,df_value], sort=True, axis=1)

print(full_df)


del full_df["nestedData"]

print(full_df)

输出 -

  Main_ID SetID  Version  Time  Value
0       1  1041      2.0  5000      1
1     NaN   NaN      NaN  6000      2
2     NaN   NaN      NaN  7000      3

标签: pythonpandas

解决方案


用于json_normalize将 dict 展平为数据框,然后用于explode将列表转换为行:

stream= {
    "Outerclass": {
        "Main_ID": "1",
        "SetID": "1041",
        "Version": 2,
        "nestedData": {
            "time": ["5000", "6000", "7000"],
            "value": [1, 2, 3]
        }

    } }
df = pd.json_normalize(stream)
df = df.apply(pd.Series.explode).reset_index(drop=True)
print(df)


  Outerclass.Main_ID Outerclass.SetID  Outerclass.Version Outerclass.nestedData.time Outerclass.nestedData.value
0                  1             1041                   2                       5000                           1
1                  1             1041                   2                       6000                           2
2                  1             1041                   2                       7000                           3

推荐阅读