python - 如何在流数据中将复杂字典创建到 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
解决方案
用于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
推荐阅读
- python - TypeError: 最小的 Django 应用程序中的预期 str、字节或 os.PathLike 对象,而不是元组
- javascript - 在 JavaScript 中生成不重复的随机数
- react-native - 如何编程 React-native-navigation 导航栏后退按钮(不是硬件按钮)?
- vb.net - 带有复选框删除的 Visual Studio 2015 错误消息页面
- html - 如何使登录页面显示在单独的页面上(当前有旁边菜单) ASP.net MVC
- python - 在Python中通过数字乘数填充数组元素
- ios - 我可以使用一个视图控制器来处理标签栏控制器中的多个视图吗
- android-studio - 在 Android Studio 中创建新文件夹是空的(这里什么都没有)
- php - Curl:获取 Instagram 帐户关注者数量
- architecture - 该图是有效的 UML 组件图吗?