How to Avoid Creating an Index when Saving a CSV File in Pandas

Spread the love

Problem –

You want to write a pandas dataframe to a csv file but when you do a index is getting added to the file and You want to avoid it.

Solution –

Let’s read a dataset to explain it.

import pandas as pd

url = ''
df = pd.read_csv(url)

Now let’s try to write this dataframe to a csv file without any modifications.


Now, if I look into the csv file you will see that an index is getting added.

To avoid adding this index when writing a dataframe to a csv file, we can use the index=False argument.

Let’s try again and see the changes.

df.to_csv('./new_stock_prices2.csv', index=False)

We can see that no index has been added this time.

Related Posts –

  1. Pandas to_csv – write a dataframe to a csv file.
  2. Pandas read_csv() – read a csv file in Python.

Rating: 1 out of 5.

Leave a Reply