how to convert dataframe to csv in python

To convert a DataFrame to a CSV file in Python using the pandas library, you can use the to_csv() function.

Here is an example:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John', 'Mike', 'Sarah'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)

# Convert DataFrame to CSV file
df.to_csv('output.csv', index=False)
272 chars
12 lines

In this example, we first import the pandas library. Then, we create a sample DataFrame called df.

Next, we use the to_csv() function to convert the DataFrame to a CSV file. We specify the file name as 'output.csv' and set index=False to omit the row index in the output.

After running this code, a CSV file named 'output.csv' will be created in the current working directory containing the contents of the DataFrame.

Remember to replace 'output.csv' with the desired name and path for your CSV file.

Make sure you have the pandas library installed by running pip install pandas before executing this code.

related categories

gistlibby LogSnag