Sitemap
Zeeshan Ali

Zeeshan Ali

I am a Python developer and I am here to share what i have learnt so far. Hope my posts will help you in your python development journey. www.letmeflutter.com

Python Dataframe to CSV File Generation

1 min readJul 19, 2023

To save a Python DataFrame to a CSV (Comma-Separated Values) file, you can use the to_csv() method provided by pandas library, assuming you have pandas installed. Here's how you can do it:

pip install pandas

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

In case you don’t have pandas installed in your system, then run this command in your terminal or cmd.

import pandas as pd

# Creating a dictionary that represents the data
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 22, 28],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago'],
'Salary': [50000, 60000, 45000, 55000]
}

# Creating the DataFrame
df = pd.DataFrame(data)

# If you want to save the DataFrame to a CSV file without including the index:
df.to_csv('output.csv', index=False)

# If you want to save the DataFrame to a CSV file and include the index:
df.to_csv('output.csv', index=True)

In the above code, df is the name of your DataFrame, and we are using the to_csv() method to save it to a file named "output.csv". The index parameter is used to specify whether you want to include the row index in the CSV file. Setting index=False will exclude the index, while index=True (which is the default) will include it.

Make sure you have pandas installed before running the code. If you don’t have it installed, you can install it using pip:

pip install pandas

Once you run the code, your DataFrame will be saved as a CSV file named “output.csv” in the current working directory.

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Python developer and I am here to share what i have learnt so far. Hope my posts will help you in your python development journey. www.letmeflutter.com