How to Create CSV File From Dataframe in Python

To create a CSV file from a dataframe in Python, you can use the to_csv() function from the pandas library.

The following example shows how to create a CSV file from a dataframe using the to_csv() function in Python.

Using to_csv() Function

We can use the to_csv() function to create a CSV file from a dataframe.

Let’s see how to use the to_csv() function in Python:

# Import pandas library
import pandas as pd

# Create the DataFrame
office_stuff = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Create CSV file from dataframe
office_stuff.to_csv("data.csv")

In this example, we use the to_csv() function to create a CSV file data.csv from the dataframe office_stuff.

The output shows the CSV file created from the dataframe.

Conclusion

We can use the to_csv() function from the pandas library to create a CSV file from a dataframe in Python.