首页 > 解决方案 > 将行放在标题下方时,pandas.read_csv 会导致列标签移位

问题描述

我正在尝试使用 pandas 读取 .csv 文件,其标题如下所示:

System Information_1
System Information_2
System Information_3
System Information_4

"Label1"; "Label2"; "Label3"; "Label4"; "Label5"; "Label6"
"alternative Label1"; "alternative Label2"; "alternative Label3"; "alternative Label4"; "alternative Label5"; "alternative Label6"
"unit1"; "unit2"; "unit3"; "unit4"; "unit5"; "unit6"

我正在使用以下代码来阅读它:
df = pd.read_csv('data.csv', sep=';', header=5, skiprows=[6,7], encoding='latin1')

然而,我的数据框最终没有"unit1", "unit2", "unit3", "unit4", "unit5", "unit6"作为"Label1", "Label2", "Label3", "Label4", "Label5", "Label6"列标签。

但是,在我的 csv 文件的旧版本中,导入代码可以正常工作。我可以发现文件之间的区别是旧文件在前 4 行中有完整的分隔符集:

System Information_1;;;;;
System Information_2;;;;; 
etc.  

有谁知道该错误来自哪里以及如何解决?

标签: pythonpandascsv

解决方案


你也可以跳过第一行,但也不要将 header 设置为5,因为它是 0 ,所以你可以让它被自动检测:

df = pd.read_csv('data.csv', sep=';', skiprows=[0,1,2,3,4,6,7], encoding='latin1')

推荐阅读