Home > Backend Development > Python Tutorial > How to Save Pandas DataFrames as CSV without Indexes?

How to Save Pandas DataFrames as CSV without Indexes?

Susan Sarandon
Release: 2024-10-29 17:08:02
Original
725 people have browsed it

How to Save Pandas DataFrames as CSV without Indexes?

Saving Pandas DataFrames as CSV without Indexes

When saving a CSV file from a Pandas DataFrame, it's common to encounter an additional column containing indexes. This can be undesirable in certain scenarios. This article provides a solution to avoid the creation of these indexes in the output CSV file.

Problem Statement:

How to prevent Pandas from adding an index column while saving a DataFrame to a CSV file?

Solutions:

The key to avoiding index creation is to set the index parameter to False when using the to_csv method:

<code class="python">df.to_csv('your.csv', index=False)</code>
Copy after login

This argument instructs Pandas to exclude the index column from the output CSV file.

Example:

Consider the following DataFrame:

<code class="python">import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie'],
        'age': [20, 30, 40]}
df = pd.DataFrame(data)</code>
Copy after login

Without index=False:

<code class="python">df.to_csv('output.csv')</code>
Copy after login

This will create a CSV file with the following content:

,name,age
0,Alice,20
1,Bob,30
2,Charlie,40
Copy after login

Note the presence of the index column with values 0, 1, and 2.

With index=False:

<code class="python">df.to_csv('output2.csv', index=False)</code>
Copy after login

This time, the output CSV file will look like this:

name,age
Alice,20
Bob,30
Charlie,40
Copy after login

As you can see, the index column has been successfully excluded.

Remember to apply the index=False argument each time you save a DataFrame to CSV to avoid unwanted index creation.

The above is the detailed content of How to Save Pandas DataFrames as CSV without Indexes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template