Pandas处理JSON资产数据:过滤无效条目、缺失字段与CVE聚合
Pandas处理JSON资产数据解决方案
准备工作:读取JSON数据
假设你的JSON数据存储在文件assets.json中,先读取为DataFrame:
import pandas as pd # 读取JSON数据,根据实际结构调整orient参数(比如'records') df = pd.read_json('assets.json', orient='records')
步骤1:过滤severity_modification_type为NONE的条目
直接用布尔索引过滤目标条目:
# 过滤掉severity_modification_type等于NONE的行 df_filtered = df[df['severity_modification_type'] != 'NONE']
步骤2:填充缺失的CVE字段
针对嵌套的plugin.cve字段,用apply结合字典get方法处理缺失值:
# 处理plugin.cve字段,缺失时填充"No CVE" df_filtered['cve'] = df_filtered['plugin'].apply(lambda x: x.get('cve', 'No CVE')) # 若plugin字段本身可能缺失,增加类型判断: # df_filtered['cve'] = df_filtered['plugin'].apply(lambda x: x.get('cve', 'No CVE') if isinstance(x, dict) else 'No CVE')
步骤3:聚合同一hostname的CVE
通过groupby分组后,用str.join实现CVE的逗号分隔聚合:
# 按hostname分组,将cve字段用逗号拼接 df_aggregated = df_filtered.groupby('hostname')['cve'].agg(', '.join).reset_index()
完整示例演示
示例JSON数据
[ {"hostname": "server-01", "severity_modification_type": "NONE", "plugin": {"cve": "CVE-2023-1234"}}, {"hostname": "server-01", "severity_modification_type": "MODIFIED", "plugin": {"cve": "CVE-2023-5678"}}, {"hostname": "server-02", "severity_modification_type": "MODIFIED", "plugin": {}}, {"hostname": "server-02", "severity_modification_type": "MODIFIED", "plugin": {"cve": "CVE-2023-9012"}} ]
期望输出
| hostname | cve |
|---|---|
| server-01 | CVE-2023-5678 |
| server-02 | No CVE, CVE-2023-9012 |
常见问题排查
- 过滤不生效:检查
severity_modification_type字段的拼写、大小写是否匹配,可通过df['severity_modification_type'].unique()查看所有取值。 - CVE填充不生效:确认
plugin字段为字典类型,若存在非字典值,需添加类型判断(如代码注释部分)。 - 聚合不生效:检查
hostname字段是否存在空格或隐藏字符,可先执行df_filtered['hostname'] = df_filtered['hostname'].str.strip()清理字段。
内容的提问来源于stack exchange,提问作者LObermeyer
相关产品推荐
相关产品推荐

