使用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'
排查步骤
- 核对文件路径与名称:代码中写的是
pd.read_csv('scan.csv'),但错误栈显示实际读取的是scan_images.csv,确认读取的目标文件是否正确,避免因文件错误导致列名不匹配。 - 确认CSV列名:检查目标CSV文件的表头,确认是否存在名为
vulnerability的列——可能存在拼写错误、大小写差异(如Vulnerability)、表头包含空格(如vulnerability)或特殊字符。 - 查看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
相关产品推荐
相关产品推荐

