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

使用Pandas处理CSV统计CVE类型时遭遇KeyError问题求助

排查Pandas统计CVE时的KeyError问题

问题背景

原本计划用批处理脚本遍历CSV某一列的CVE值并统计数量,改用Pandas编写代码后,运行时抛出KeyError: 'vulnerability'错误,代码意图是统计以(C)、(H)结尾的CVE值出现次数。

错误信息

KeyError                                  Traceback (most recent call last)
File c:\Users\hello\OneDrive\Documents\python\scan_pd.py:6
      3 df = pd.read_csv('scan_images.csv')
      5 # Filtrer les lignes se terminant par (C)
----> 6 c_rows = df[df['vulnerability'].str.endswith('(C)')]
      8 # Compter les occurrences de chaque valeur 
...
   3815     #  InvalidIndexError. Otherwise we fall through and re-raise
   3816     #  the TypeError.
   3817     self._check_indexing_error(key)

KeyError: 'vulnerability'

排查步骤

  1. 核对文件路径与名称:代码中写的是pd.read_csv('scan.csv'),但错误栈显示实际读取的是scan_images.csv,确认读取的目标文件是否正确,避免因文件错误导致列名不匹配。
  2. 确认CSV列名:检查目标CSV文件的表头,确认是否存在名为vulnerability的列——可能存在拼写错误、大小写差异(如Vulnerability)、表头包含空格(如vulnerability)或特殊字符。
  3. 查看DataFrame列名:在读取CSV后添加打印列名的代码,确认实际加载的列:
    import pandas as pd
    df = pd.read_csv('scan.csv')
    print("当前DataFrame的列名:", df.columns.tolist())
    

修正后的示例代码

假设CSV中实际列名是vulnerability,且文件路径正确,同时处理可能的空值避免报错:

import pandas as pd

# 确认读取正确的文件
df = pd.read_csv('scan.csv')

# 先检查列名是否存在
if 'vulnerability' not in df.columns:
    print("错误:CSV文件中不存在'vulnerability'列")
    print("当前列名:", df.columns.tolist())
else:
    # 过滤并统计以(C)结尾的CVE,处理空值
    c_counts = df[df['vulnerability'].dropna().str.endswith('(C)')]['vulnerability'].value_counts()
    # 过滤并统计以(H)结尾的CVE,处理空值
    h_counts = df[df['vulnerability'].dropna().str.endswith('(H)')]['vulnerability'].value_counts()

    print("Occurrences of values ending with (C):")
    print(c_counts)

    print("\nOccurrences of values ending with (H):") 
    print(h_counts)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:28:19