Python循环合并CSV文件遇KeyError:2错误,求排查
排查Pandas合并CSV时的KeyError:2问题
问题重现
尝试用以下Python代码循环合并两个CSV文件:
df_source1 = pd.read_csv("3_2_conv_perc_1.csv") df_source2 = pd.read_csv("3_2_conv_perc_{}.csv".format(i)) df_source1[f'column_{i}'] = df_source2[2]
运行后触发KeyError: 2,报错信息如下:
>>> df_source1[f'column_{i}'] = df_source2[2] Traceback (most recent call last): File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3652, in get_loc return self._engine.get_loc(casted_key) File "pandas\_libs\index.pyx", line 147, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\index.pyx", line 176, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 2 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\frame.py", line 3761, in __getitem__ indexer = self.columns.get_loc(key) File "C:\PROGRA~1\QGIS33~1.2\apps\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3654, in get_loc raise KeyError(key) from err KeyError: 2
CSV文件数据样例:
0 1 2 0 500 1299500 0 1 1500 1299500 0 2 2500 1299500 0 3 3500 1299500 0 4 4500 1299500 0
错误原因
KeyError: 2说明df_source2中不存在整数索引为2的列,核心问题出在Pandas读取CSV时的列名解析不符合预期:
- 若CSV没有表头,第一行就是数据,默认
pd.read_csv()会把第一行当作列名,此时列名是带大量前导空格的字符串(比如' 0'、' 2'),而非整数2; - 若CSV第一行是表头,但表头包含前导空格,直接用整数
2访问列会失败。
解决方案
根据CSV实际情况选择对应方案:
方案1:CSV无表头,第一行是数据
读取时指定header=None,让Pandas自动用整数0、1、2作为列名:
df_source1 = pd.read_csv("3_2_conv_perc_1.csv", header=None) df_source2 = pd.read_csv("3_2_conv_perc_{}.csv".format(i), header=None) df_source1[f'column_{i}'] = df_source2[2]
方案2:CSV第一行是带空格的表头
添加skipinitialspace=True参数,让Pandas自动忽略列名的前导空格,此时列名会被解析为'0'、'1'、'2'的字符串,用字符串索引访问即可:
df_source1 = pd.read_csv("3_2_conv_perc_1.csv", skipinitialspace=True) df_source2 = pd.read_csv("3_2_conv_perc_{}.csv".format(i), skipinitialspace=True) # 用字符串索引访问第三列 df_source1[f'column_{i}'] = df_source2['2']
验证方法
可以先打印df_source2.columns查看实际列名,确认问题根源:
df_source2 = pd.read_csv("3_2_conv_perc_{}.csv".format(i)) print(df_source2.columns)
内容的提问来源于stack exchange,提问作者Ark Lomas
相关产品推荐
相关产品推荐

