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

Python多层嵌套JSON按层级统计空值,三级字段子字段全空如何计数

实现代码

你可以按以下步骤完成分级空值统计,针对fields.System.AssignedTo这类三级嵌套字段的特殊统计规则也适配:

方案1:全量统计1、2、3级所有字段的空值

import pandas as pd

# 你已有的JSON规范化代码
df_norm = pd.json_normalize(json_data)
all_cols = df_norm.columns.tolist()

# 可选预处理:如果存在空字符串、None类空值,统一转为pandas可识别的空值格式
df_norm = df_norm.replace(['', None], pd.NA)

# 定义父级字段空值判断逻辑:子列全为空则父级计为空
def is_parent_level_null(row, parent_prefix):
    child_cols = [col for col in all_cols if col.startswith(f"{parent_prefix}.")]
    return row[child_cols].isnull().all()

# 提取各级字段前缀
level1_cols = [col for col in all_cols if '.' not in col]
level2_prefixes = list(set(['.'.join(col.split('.')[:2]) for col in all_cols if col.count('.') >= 1]))
level3_prefixes = list(set(['.'.join(col.split('.')[:3]) for col in all_cols if col.count('.') >= 2]))

null_result = {}

# 统计1级字段空值
for col in level1_cols:
    null_result[f"1级_{col}"] = df_norm.groupby('id')[col].apply(lambda x: x.isnull().sum()).sum()

# 统计2级字段空值
for prefix in level2_prefixes:
    if prefix in all_cols:
        null_result[f"2级_{prefix}"] = df_norm.groupby('id')[prefix].apply(lambda x: x.isnull().sum()).sum()
    else:
        df_norm[f"tmp_{prefix}"] = df_norm.apply(lambda x: is_parent_level_null(x, prefix), axis=1)
        null_result[f"2级_{prefix}"] = df_norm.groupby('id')[f"tmp_{prefix}"].sum().sum()
        del df_norm[f"tmp_{prefix}"]

# 统计3级字段空值(含你需要的fields.System.AssignedTo)
for prefix in level3_prefixes:
    df_norm[f"tmp_{prefix}"] = df_norm.apply(lambda x: is_parent_level_null(x, prefix), axis=1)
    null_result[f"3级_{prefix}"] = df_norm.groupby('id')[f"tmp_{prefix}"].sum().sum()
    del df_norm[f"tmp_{prefix}"]

# 输出格式化结果
stats_df = pd.Series(null_result).reset_index()
stats_df.columns = ["字段标识", "空值总数"]
print(stats_df)

方案2:仅单独统计fields.System.AssignedTo的空值

如果不需要全量分级统计,只需要目标三级字段的空值,可直接用简化代码:

import pandas as pd

df_norm = pd.json_normalize(json_data)
df_norm = df_norm.replace(['', None], pd.NA)

# 提取AssignedTo下的所有子列
assigned_child_cols = [col for col in df_norm.columns if col.startswith("fields.System.AssignedTo.")]
# 判断每行AssignedTo是否全空
df_norm["assigned_to_null"] = df_norm[assigned_child_cols].isnull().all(axis=1)
# 按ID分组统计空值总数
assigned_null_count = df_norm.groupby("id")["assigned_to_null"].sum().sum()
print(f"fields.System.AssignedTo 空值总数:{assigned_null_count}")

说明

  • 如果不需要按ID分组聚合总空值,只需要每行维度的统计结果,去掉外层.sum()即可
  • 代码默认按你给出的规则执行:嵌套父级字段下所有子孙列全为空时,才会计为父级字段的1次空值

内容的提问来源于stack exchange,提问作者v-jh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:27:09