python - 将行放在标题下方时,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.
有谁知道该错误来自哪里以及如何解决?
解决方案
你也可以跳过第一行,但也不要将 header 设置为5
,因为它是 0 ,所以你可以让它被自动检测:
df = pd.read_csv('data.csv', sep=';', skiprows=[0,1,2,3,4,6,7], encoding='latin1')
推荐阅读
- javascript - 具有许多子模块的打字稿项目
- bash - Bash 使用分隔符“,”拆分字符串并在字符串中保留空格
- javascript - 我如何在函数内部的函数中获取返回值?
- c++ - 可变参数模板模板的完美转发
- php - 如何更新字段以将值推送到 Laravel 中的现有值
- ios - 结合两个文本字段验证功能
- javascript - 基于此现有数组对象创建新的多维数组
- shell - 休眠调试指令 UNIX Shell 脚本
- javascript - React Native Flatlist 在数据更新时多次渲染同一个项目
- lua - 为什么在远程事件中运行此函数时出现“无法将值转换为对象”?