Pandas.read_csv将行放在标题下方时导致列标签移位

2024-04-24 04:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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"而不是{}作为列标签。在

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

^{2}$

有人知道这个错误从何而来,如何解决它吗?在


Tags: 文件csvinformationsystemlabel2label1alternativeunit2
3条回答

“header”参数在“skiprows”参数之后开始计数。在

如果要将标签用作页眉:

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

其他情况下,如果要使用替代标签作为标题:

^{pr2}$

我可以用标签来保存数据。在

可以使用列表作为头参数:

import pandas as pd
from io import StringIO

data = """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" 
1;2;3;4;5;6
10;20;30;40;50;60
"""

df = pd.read_csv(StringIO(data), sep=';', header=[4], skiprows=[6, 7], encoding='latin1')

给出:

enter image description here

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

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

相关问题 更多 >