Writing a pandas DataFrame to CSV file

Created by Andy HaydenLinked to 71.9m issues across 87 teams

tl;dr

Here's how to write a pandas DataFrame to a CSV file.

First, import the pandas library:

import pandas as pd

Next, create a DataFrame:

df = pd.DataFrame(data)

Finally, use the to_csv method to write the DataFrame to a CSV file. To delimit by a tab, use the sep argument:

df.to_csv(file_name, sep=' ')

If you want to use a specific encoding (e.g. 'utf-8'), use the encoding argument:

df.to_csv(file_name, sep=' ', encoding='utf-8')