Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas read_csv function is reading csv header wrong

Tags:

python

pandas

csv

See example csv file below:

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?

like image 516
pr338 Avatar asked Mar 14 '23 10:03

pr338


1 Answers

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

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

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 names argument is not passed.
  • sep=',' , seperator is ',' by default.
like image 139
Anand S Kumar Avatar answered Mar 19 '23 05:03

Anand S Kumar