You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas含JSON的列展开为新列?处理空值与未知键

解决DataFrame中含NULL的JSON列展开问题

一、提取指定7个字段(优先推荐)

针对你只需要特定字段的需求,直接处理目标字段,同时兼容NULL值和字段缺失的场景:

  1. 定义目标字段列表:
target_fields = ['VCPUs', '字段2', '字段3', '字段4', '字段5', '字段6', '字段7']  # 替换为你的实际字段名
  1. 编写处理函数,覆盖NULL、格式错误JSON和字段缺失情况:
import json
import pandas as pd

def extract_target_fields(row):
    info = row['additionalInfo']
    # 处理空值/NULL
    if pd.isna(info) or info.strip() == '':
        return {f: None for f in target_fields}
    # 解析JSON,处理格式错误
    try:
        json_data = json.loads(info)
        # 用get方法安全获取字段,不存在则返回None
        return {f: json_data.get(f) for f in target_fields}
    except json.JSONDecodeError:
        return {f: None for f in target_fields}
  1. 应用函数并合并到原DataFrame:
# 提取字段并转为DataFrame
extracted_cols = df1.apply(extract_target_fields, axis=1, result_type='expand')
# 合并原表与提取的新列
final_df = pd.concat([df1, extracted_cols], axis=1)

二、展开所有JSON字段(兼容NULL)

如果需要展开JSON中所有字段,先预处理additionalInfo列消除NULL影响,再用json_normalize:

import json
import pandas as pd

# 预处理:将NULL/空值转为空字典,有效JSON转为字典对象
processed_info = df1['additionalInfo'].map(
    lambda x: json.loads(x) if pd.notna(x) and x.strip() != '' else {}
)
# 展开所有JSON字段
expanded_cols = pd.json_normalize(processed_info)
# 合并到原表
final_df = pd.concat([df1, expanded_cols], axis=1)

三、大数据量优化(针对GB级Azure文件)

面对几GB的数据集,常规apply效率较低,可通过以下方式优化:

  • 使用swifter加速apply(需先安装:pip install swifter):
import swifter
extracted_cols = df1.swifter.apply(extract_target_fields, axis=1, result_type='expand')
  • 分块读取处理:避免一次性加载全量数据到内存
chunk_size = 100000  # 根据机器内存调整大小
result_chunks = []

# 分块读取源文件(假设是CSV格式)
for chunk in pd.read_csv('azure_usage_file.csv', chunksize=chunk_size):
    processed_chunk = chunk.apply(extract_target_fields, axis=1, result_type='expand')
    result_chunks.append(pd.concat([chunk, processed_chunk], axis=1))

# 合并所有分块结果
final_df = pd.concat(result_chunks, ignore_index=True)

内容的提问来源于stack exchange,提问作者fr0do007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:50:31