Remove index column while saving csv in pandas

71,021

Solution 1

What you are seeing is the index column. Just set index=False:

df_csv = df0_fa.to_csv('revenue/data/test.csv',mode = 'w', index=False)

Solution 2

To read the csv file without indexing you can unset the index_col to prevent pandas from using your first column as an index. And while saving the csv back onto the disk, do not forget to set index = false in to_csv. This will not generate an additional index column. Else, if you need to delete/remove a specific column from the data frame, use drop , it worked for me as follows :

import pandas as pd
file_path = 'example_file.csv'
data_frame = pd.read_csv(file_path, index_col = False)
column_name = 'column'
data_frame = data_frame.drop(column_name, axis = 1) 
data_frame.to_csv(file_path, index = False)

In this case, even if your csv has a valid index column, you can skip index_col = False in read_csv.

Share:
71,021
JPC
Author by

JPC

Updated on January 16, 2022

Comments

  • JPC
    JPC over 1 year

    I'm trying to create a csv with pandas, but when I export the data to csv it gives me an extra column

    d = {'one' : pd.Series([1., 2., 3.]),'two' : pd.Series([1., 2., 3., 4.])}
    df0_fa = pd.DataFrame(d)
    df_csv = df0_fa.to_csv('revenue/data/test.csv',mode = 'w')
    

    Thus, my result is:

     ,one,two
    0,1.0,1.0
    1,2.0,2.0
    2,3.0,3.0
    3,4.0,4.0
    

    But, the expected results are:

    one,two
    1.0,1.0
    2.0,2.0
    3.0,3.0
    4.0,4.0
    
  • Blairg23
    Blairg23 over 7 years
    I don't know how I missed this in the documentation, but great catch! That was frustrating me forever, trying to figure out where I added the index as a column.
  • JD Long
    JD Long over 7 years
    I banged my head against that more than I should have as well.
  • twiz
    twiz almost 7 years
    And in case anyone is also trying to remove the column names, you can pass in header=False.