Pandas DataFrame to CSV


Are you working in Python and needing to export the data in your pandas DataFrame out to a CSV (comma separated values) text file?

Let’s create a pandas DataFrame manually. I created a Jupyter Notebook project in Anaconda Navigator to test how this works. This will be our “friends” dataset.

import pandas as pd
data = {'firstname': ['Bobby', 'Linda', 'Suzie', 'Rowan'],
       'amount': [12, 67, 33, 41]}
df = pd.DataFrame(data)
df

Now let’s export the data to a CSV file.

df.to_csv(r'D:\Test\friends_2.csv')

Below is what the text file looks like when you open it in Notepad++.

,firstname,amount
0,Bobby,12
1,linda,67
2,Suzie,33
3,Rowan,41

Notice that the first column does not have a name. We can add a name to this index column.

df.index.name='Index1'
df

We can now export the DataFrame to a CSV file like we did above.

Leave a Reply