Export Pandas DataFrame to CSV Format

Let's find out how to convert a pandas DataFrame to CSV format.

We'll cover the following

Try it yourself

Try executing the code below to see the result.

Press + to interact
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns=['x', 'y'])
print(df.to_csv())

Explanation

What’s going on in the unnamed column with 0 and 1 values?

The pandas.DataFrame documentation has this to say:

“Data structure also contains labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.”

The labeled axis for rows is called the index. When we convert a pandas.DataFrame to another format (for example, CSV or SQL), it will add the index by default.

We can use index=False to omit the index.

In [1]: print(df.to_csv(index=False))
x,y
1,2
3,4

Solution

Press + to interact
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns=['x', 'y'])
print(df.to_csv(index=False))

Get hands-on with 1300+ tech skills courses.