How to Export Pandas DataFrame to CSV (+Example)

5/5 - (1 vote)

To export/convert a Pandas DataFrame to a CSV file, use the Pandas method to_csv(). Set the index=False argument if you don’t want the first column to be the index number in the CSV, which is usually the case.

Let’s dive into a simple two-step example on how to convert a DataFrame to a CSV easily and without stress. πŸ§˜β€β™€οΈ

Step 1: Create DataFrame

You can create the Pandas DataFrame using various ways such as passing a dictionary into the pd.DataFrame() function:

import pandas as pd

# Create the DataFrame
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Carl', 'Dave'],
                   'Age': [23, 24, 19, 33],
                   'Income': [99000, 88000, 21000, 129000]})

# Print the DataFrame
    Name  Age  Income
0  Alice   23   99000
1    Bob   24   88000
2   Carl   19   21000
3   Dave   33  129000

🌍 Related Tutorial: How to Create a Pandas DataFrame?

Step 2: Export DataFrame to CSV File

The Pandas to_csv() function allows you to export a DataFrame into a CSV file directly and without any additional overhead. You can set the index=False argument if you don’t want the first column to be the index number in the CSV, which is usually the case.

Here’s the function applied to our example:

df.to_csv('my_file.csv', index=False)

The resulting CSV file looks like this, well without my note that this doesn’t have an index.

If you’d forget the index=False argument, Pandas would convert with a row index, so the file would look like this:

df.to_csv('my_file.csv') # index=True per default

🌍 Related Tutorial: The Ultimate Guide to pd.to_csv()

How to Convert DataFrame to CSV String?

If you want the DataFrame converted into a CSV string rather than a CSV file, just use the pd.to_csv() function without any filename or path argument. In that case, a CSV string is returned that you can use for further processing in your Python script.

Here’s an example:

# Convert DataFrame to CSV
csv_string = df.to_csv()

# Print the CSV string

You can modify this output by passing the index=False argument:

# Convert DataFrame to CSV (no index)
csv_string = df.to_csv(index=False)

# Print the CSV string

🌍 Related Tutorial: How to Convert a Pandas DataFrame to a CSV String?

Programmer Humor

πŸ‘±β€β™€οΈ Programmer 1: We have a problem
πŸ§”β€β™‚οΈ Programmer 2: Let’s use RegEx!
πŸ‘±β€β™€οΈ Programmer 1: Now we have two problems

… yet – you can easily reduce the two problems to zero as you polish your “RegEx Superpower in Python“. πŸ™‚