Pandas – Convert DataFrame to CSV

Pandas – Convert DataFrame to CSV String

To convert a DataFrame to CSV (Comma Separated Values) string in Pandas, call DataFrame.to_csv() function and pass the required arguments.

Syntax

The syntax to convert a DataFrame df to CSV is

df.to_csv()

By default, the index of the DataFrame is also converted to CSV. If index has to be excluded in the CSV output, then pass index=False as argument.

df.to_csv(index=False)

Examples

1. Convert given DataFrame df to a CSV string

In this example, we take a DataFrame with five rows, and convert this DataFarme to CSV using DataFrame.to_csv() function.

Python Program

import pandas as pd

df = pd.DataFrame({'name':['a', 'b', 'c', 'd', 'e'],
                   'age' :[20, 21, 20, 19, 21]})
result = df.to_csv()
print(result)
Run Code Copy

Output

,name,age
0,a,20
1,b,21
2,c,20
3,d,19
4,e,21

2. Convert given DataFrame df to a CSV string by ignoring the index.

Now, let us convert the DataFrame to CSV, ignoring index. Pass index=False to the DataFrame.to_csv() method.

Python Program

import pandas as pd

df = pd.DataFrame({'name':['a', 'b', 'c', 'd', 'e'],
                   'age' :[20, 21, 20, 19, 21]})
result = df.to_csv(index=False)
print(result)
Run Code Copy

Output

name,age
a,20
b,21
c,20
d,19
e,21

Summary

In this Pandas Tutorial, we learned how to convert a DataFrame to CSV String.

Related Tutorials

Code copied to clipboard successfully 👍