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 print(df) ''' 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 print(csv_string) ''' ,Name,Age,Income 0,Alice,23,99000 1,Bob,24,88000 2,Carl,19,21000 3,Dave,33,129000 '''
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 print(csv_string) ''' Name,Age,Income Alice,23,99000 Bob,24,88000 Carl,19,21000 Dave,33,129000 '''
π 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“. π