How to write a Pandas DataFrame to a .csv file in Python

Pandas is very useful for CSV processing. In this post, I will show you how to write a Pandas DataFrame to a .csv file in Python.

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

Writing a DataFrame to a .csv file #

Let check an example.

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)

index=False means that the index column will not be written to the .csv file. The default value is True. The above code will output the following to the file example.csv:

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.

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

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

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.

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:

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

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

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

The new output will be:

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.