How to avoid Python/Pandas creating an index in a saved csv?

How to avoid Python/Pandas creating an index in a saved csv?

Use index=False.

df.to_csv(your.csv, index=False)

There are two ways to handle the situation where we do not want the index to be stored in csv file.

  1. As others have stated you can use index=False while saving your
    dataframe to csv file.

    df.to_csv(file_name.csv,index=False)

  2. Or you can save your dataframe as it is with an index, and while reading you just drop the column unnamed 0 containing your previous index.Simple!

    df.to_csv( file_name.csv )
    df_new = pd.read_csv(file_name.csv).drop([unnamed 0],axis=1)

How to avoid Python/Pandas creating an index in a saved csv?

If you want no index, read file using:

import pandas as pd
df = pd.read_csv(file.csv, index_col=0)

save it using

df.to_csv(file.csv, index=False)

Leave a Reply

Your email address will not be published. Required fields are marked *