How to write Pandas DataFrame to CSV File

Haris Bin Nasir Avatar

·

·

Pandas is a great tool for working with CSV files. I’ll show you how to write a Pandas DataFrame to a.csv file in Python in this post.

To write a Pandas DataFrame to a .csv file, you need to use the to_csv() method.

Writing a DataFrame to a .csv file

Below is an example on how to write Pandas Dataframe to CSV file.

Copied!
import pandas as pd df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': [6, 7, 8, 9, 10]}) print(df) # Output # col1 col2 # 0 1 6 # 1 2 7 # 2 3 8 # 3 4 9 # 4 5 10 df.to_csv('example.csv', index=False)

The index column will not be written to the.csv file if index=False is used. True is the default value. The following will be written to the file example.csv by the code above:

Copied!
col1,col2 1,6 2,7 3,8 4,9 5,10

Change the delimiter

If you want to change the delimiter, you can use the sep parameter.

Copied!
df.to_csv('example.csv', index=False, sep=';')

The above code will output the following to the file example.csv:

Copied!
col1;col2 1;6 2;7 3;8 4;9 5;10

Change the datetime format

If your data has a datetime format, you can use the date_format parameter.

Let check an example.

Copied!
import pandas as pd from datetime import datetime df = pd.DataFrame({ 'Datetime': [datetime(2021, 10, 26), datetime(2021, 10, 27)], 'Todo': ['Write Python Tutorial', 'Read Javascript documentaion'] }) df.to_csv('example.csv', index=False)

The above code will output the following to the file example.csv:

Copied!
Datetime,Todo 2021-10-26,Write Python Tutorial 2021-10-27,Read Javascript documentaion

Let change the datetime format to %B %d %y.

Copied!
df.to_csv('example.csv', index=False, date_format='%B %d %y')

The new output will be:

Copied!
Datetime,Todo October 26 21,Write Python Tutorial October 27 21,Read Javascript documentaion

Further reading: Read more about Pandas’s DataFrame.to_csv() method in the Pandas documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *