How to export a Pandas DataFrame to CSV in Python
Published on Aug. 22, 2023, 12:15 p.m.
To export a Pandas DataFrame to CSV in Python, you can use the to_csv()
method of the DataFrame object. The method allows you to specify the path or file object where the CSV should be written, as well as various other options for formatting the output.
Here is an example:
import pandas as pd
my_data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['New York', 'Paris', 'London']}
df = pd.DataFrame(my_data)
df.to_csv('my_data.csv', index=False)
This imports the Pandas library, creates a DataFrame object from a dictionary, and then writes the data to a CSV file called my_data.csv
in the current directory. The index
parameter is set to False
to exclude the index column from the output.
You can also specify other options such as the delimiter, header row, and encoding using keyword arguments to the to_csv()
method. For more information, you can refer to the Pandas documentation on the to_csv()
method.