How to 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.
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.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedInRelated Article - Pandas DataFrame
- How to Get Pandas DataFrame Column Headers as a List
- How to Delete Pandas DataFrame Column
- How to Convert Pandas Column to Datetime
- How to Convert a Float to an Integer in Pandas DataFrame
- How to Sort Pandas DataFrame by One Column's Values
- How to Get the Aggregate of Pandas Group-By and Sum