Pandas: How to export a DataFrame to .csv

Here is a function I wrote that will export an entire DataFrame to csv. It uses the Pandas function to_csv(). Just feed it the name of the DataFrame and the name you want for the .csv file.

def dataframe_to_csv(filename, DataFrame):
    """Export entire DataFrame to csv."""
    output = DataFrame
    output.to_csv(filename, index=True)

The filename can be a full file path (or if you have your local directory defined in your Jupyter Notebook using ‘cd’, you can just use the file name itself). The function can be called like so:

dataframe_to_csv('Exported_dataframe.csv', batch_df)
# or
dataframe_to_csv('C:\Users\username\data\Exported_dataframe.csv', batch_df)

Alternatively, you may want to just export one or more columns from the DataFrame. Here is a function I wrote for that:

def partial_dataframe_to_csv(filename, DataFrame, columns):
    """Export a portion of a DataFrame to csv."""
    output = DataFrame
    # Write only the fields found in the columns list
    output = output[columns]
    output.to_csv(filename, index=False)

‘columns’ is a list that contains the column header names that you want exported. The function can be called like so:

columns_to_export = ["isPlace", "isOpen"]
partial_dataframe_to_csv("DataFrame_portion.csv", my_dataframe, columns_to_export)

For more information see: pandas.DataFrame.to_csv

Leave a Reply