欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > Pandas处理和分析嵌套JSON数据:六种方法的深入解析与比较

Pandas处理和分析嵌套JSON数据:六种方法的深入解析与比较

2025/10/16 4:36:52 来源:https://blog.csdn.net/shanxuanang/article/details/144239534  浏览:    关键词:Pandas处理和分析嵌套JSON数据:六种方法的深入解析与比较

在数据分析领域,处理和分析嵌套JSON数据是一项常见且重要的任务。本文将详细介绍六种不同的方法,用于将嵌套JSON字符串转换为结构化的Pandas DataFrame,并进行比较分析。我们将从数据初始化开始,逐步介绍每种方法的实现过程、结果展示、方法解析、优缺点以及参考文献。

数据初始化与预览

首先,我们创建一个包含订单编号和报告数据的DataFrame。报告数据是JSON编码的字符串列表,每个字符串代表一个字典,字典中包含车辆交易价格的属性和变化范围。

import pandas as pd# 示例数据
df = pd.DataFrame({'order_no': [1, 2],'repot': ['[{"车商收车价": "1.95->2.03"}, {"车商批发价": "1.99->2.07"}]','[{"车商零售价": "2.40->2.48"}, {"个人间交易价": "2.21->2.29"}]']
})print("初始化数据预览:")
print(df)

原始数据

order_norepot
1[{“车商收车价”: “1.95->2.03”}, {“车商批发价”: “1.99->2.07”}]
2[{“车商零售价”: “2.40->2.48”}, {“个人间交易价”: “2.21->2.29”}]

期望结果

order_no车商收车价车商批发价车商零售价个人间交易价
11.95->2.031.99->2.07
22.40->2.482.21->2.29

方法1:使用json_normalizeexplode

实现过程

import ast# 解析JSON字符串并展开
df['repot'] = df['repot'].apply(ast.literal_eval)
normalized = pd.json_normalize(df['repot'].explode())
df_expanded_method1 = pd.concat([df.drop('repot', axis=1), normalized], axis=1)

结果展示

print("方法1结果:")
print(df_expanded_method1)

方法2:使用applypd.Series

实现过程

df['repot'] = df['repot'].apply(ast.literal_eval)
df_expanded_method2 = df.explode('repot')
df_expanded_method2 = df_expanded_method2.apply(lambda row: pd.Series({**{'order_no': row['order_no']}, **row['repot']}), axis=1).reset_index(drop=True)

结果展示

print("方法2结果:")
print(df_expanded_method2)

方法3:使用itertuples和循环

实现过程

expanded_data_method3 = []for row in df.itertuples(index=False):for item in ast.literal_eval(row.repot):expanded_data_method3.append({**{'order_no': row.order_no}, **item})df_expanded_method3 = pd.DataFrame(expanded_data_method3)

结果展示

print("方法3结果:")
print(df_expanded_method3)

方法4:使用concat和列表推导式

实现过程

rows_method4 = []
for index, row in df.iterrows():for item in ast.literal_eval(row.repot):rows_method4.append({**{'order_no': row['order_no']}, **item})df_expanded_method4 = pd.DataFrame(rows_method4)

结果展示

print("方法4结果:")
print(df_expanded_method4)

方法5:使用apply和字典展开

实现过程

df['repot'] = df['repot'].apply(ast.literal_eval)
expanded_data_method5 = []for index, row in df.iterrows():for item in row['repot']:new_row = {'order_no': row['order_no'], **item}expanded_data_method5.append(new_row)df_expanded_method5 = pd.DataFrame(expanded_data_method5)

结果展示

print("方法5结果:")
print(df_expanded_method5)

方法6:使用concat和独立的DataFrame

实现过程


df['repot'] = df['repot'].apply(ast.literal_eval)
results_method6 = []for index, row in df.iterrows():for item in row['repot']:temp_df = pd.DataFrame([item], index=[index])temp_df['order_no'] = row['order_no']results_method6.append(temp_df)df_expanded_method6 = pd.concat(results_method6, ignore_index=True)

结果展示

print("方法6结果:")
print(df_expanded_method6)

优缺点比较

方法1:json_normalizeexplode

  • 优点:代码简洁,易于理解和维护;性能较好,特别是在处理大型数据集时。
  • 缺点:需要确保数据格式正确,否则可能会抛出异常。

方法2:applypd.Series

  • 优点:灵活,可以处理更复杂的数据结构。
  • 缺点:性能可能不如方法1,特别是在数据集较大时。

方法3:itertuples和循环

  • 优点:适用于较小的数据集,易于调试和理解。
  • 缺点:性能较差,特别是在处理大型数据集时。

方法4:concat和列表推导式

  • 优点:代码简洁,易于理解。
  • 缺点:可能不如方法1和方法2灵活。

方法5:apply和字典展开

  • 优点:灵活,可以处理更复杂的数据结构。
  • 缺点:性能可能不如方法1,特别是在数据集较大时。

方法6:concat和独立的DataFrame

  • 优点:适用于需要对每个字典项
    进行单独处理的场景。
  • 缺点:代码复杂度较高,性能可能不如方法1。

参考文献

  1. Pandas官方文档:Pandas Documentation
  2. JSON解析与处理:JSON.org
  3. Python官方文档:Python Documentation
  4. Stack Overflow:Stack Overflow
  5. W3Schools在线教程:W3Schools

通过本文的详细介绍和比较,您可以根据自己的需求和数据特点选择合适的方法来处理和分析嵌套JSON数据。希望这些方法能够帮助您更有效地进行数据分析工作。如果您有任何问题或需要进一步的帮助,请随时联系我们。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词