How to remove the first column of row number in Python pandas dataframe

problem

When using pandas' read_csv method, it will automatically add a column of row numbers by default.

Demo

The content of test.csv is as follows:

姓名,年龄
小兔子昂,8
大兔子昂,13

The test.py code is as follows:

#引入pandas库,并改成pd方便使用,(打的字就少了)
import pandas as pd 

dataframe = pd.read_csv("test.csv")
print(dataframe)

The results are as follows:

     姓名  年龄
0  小兔子昂   8
1  大兔子昂  13

It can be found that pandas automatically adds the row number when the first column is added.

solve

Add such a parameter to read_csv,index_col=0

The modified code is as follows:

#引入pandas库,并改成pd方便使用,(打的字就少了)
import pandas as pd 

dataframe = pd.read_csv("test.csv",index_col=0)
print(dataframe)

operation result

      年龄
姓名
小兔子昂   8
大兔子昂  13

copy

You can see that the line number has been removed. Although the header is wrong , the output to the file is normal.

other

If you need to open it with Excel, you need to save the csv file in ANSI encoding format, otherwise it will be garbled . At the same time, a parameter must be added to read_csv encoding="gbk", so that python can read it without error.

If you want to know more about the index_col parameter:
The difference between pandas read_csv parameter index_col = None, 0, False

Guess you like

Origin blog.csdn.net/qq_34626094/article/details/112919783