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.
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)
Code language: PHP (php)
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:
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=';')
Code language: PHP (php)
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)
Code language: JavaScript (javascript)
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')
Code language: PHP (php)
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.