Pandas read_csv 函数读取 csv 标头错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33183547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:03:33  来源:igfitidea点击:

Pandas read_csv function is reading csv header wrong

pythoncsvpandas

提问by pr338

See example csv file below:

请参阅下面的示例 csv 文件:

A,B,C 
d,e,f 
g,h,i 

The first row with the capital letters are my headings.

大写字母的第一行是我的标题

I tried this:

我试过这个:

df = pd.read_csv("example.csv", header=0, sep=",", index_col=0, parse_dates=True)

And the data frame that is created looks like this with the headings messed up.

创建的数据框看起来像这样,标题乱七八糟。

  B C 
A 
d e f
g h i

Anyone know why or how I can fix this manually?

任何人都知道为什么或如何手动解决这个问题?

回答by Anand S Kumar

The issue is that when you pass index_col=0argument to read_csv(), it takes the 0thcolumn as the index column, hence in your resulting DataFrame, Ais the index.

问题是,当您将index_col=0参数传递给 时read_csv(),它将0th列作为索引列,因此在您生成的 DataFrame 中,A是索引。

If you do not want to take Aas the index, you should just omit the index_col=0argument. Example -

如果你不想A作为索引,你应该省略index_col=0参数。例子 -

df = pd.read_csv("example.csv", parse_dates=True)

I removed some other keyword arguments as well -

我也删除了其他一些关键字参数 -

  • header=0, header is 0 by default if namesargument is not passed.
  • sep=',', seperator is ','by default.
  • header=0, 如果names未传递参数,则默认情况下标头为 0 。
  • sep=',', 分隔符是','默认的。