Convert Pandas to CSV Without Index

As you know, the index can be thought of as a reference point for storing and accessing records in a DataFrame. They are unique for each row and usually range from 0 to the last row of the DataFrame, but we can also have serial numbers, dates, and other unique columns as the index of a DataFrame.

But sometimes, while exporting or reading files, this extra index column may not be required by the user. The problem will be illustrated more clearly using the following DataFrame.

import pandas as pd

df = pd.DataFrame([[6,7,8],
                   [9,12,14],
                   [8,10,6]], columns = ['a','b','c'])

print(df)

Output:

   a   b   c
0  6   7   8
1  9  12  14
2  8  10   6

As you can see, we have an additional index added to the DataFrame, which can be avoided by the user while saving it to a file. If we want to convert this DataFrame to a CSV file without the index column, we can do it by setting the index to be False in the to_csv() function.

Example codes:

import pandas as pd

df = pd.DataFrame([[6,7,8],
                   [9,12,14],
                   [8,10,6]], columns = ['a','b','c'])

print(df)

df.to_csv("data2.csv", index = False)

Output:

   a   b   c
0  6   7   8
1  9  12  14
2  8  10   6

As seen in the output, the DataFrame does have an index, but since we set the index parameter to False, the exported CSV file won’t have that extra column.

convert Pandas to CSV without index

If we export a file with an extra index column (without setting the index parameter as False) and then try to read it we will get a weird extra column.

import pandas as pd

df = pd.DataFrame([[6,7,8],
                   [9,12,14],
                   [8,10,6]], columns = ['a','b','c'])

print(df)

df.to_csv("data2.csv")

df_new = pd.read_csv("data2.csv")

print(df_new)

Output:

   a   b   c
0  6   7   8
1  9  12  14
2  8  10   6
   Unnamed: 0  a   b   c
0           0  6   7   8
1           1  9  12  14
2           2  8  10   6

As you can see, the df_new DataFrame has an extra Unnamed column.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Pandas DataFrame

  • Convert a Float to an Integer in Pandas DataFrame
  • Count Unique Values Per Group(s) in Pandas
  • Related Article - Pandas CSV

  • Get the Aggregate of Pandas Group-By and Sum
  • Convert DataFrame Column to String in Pandas