Thursday 11 April 2024

Pandas: Export data to a CSV file

Using to_csv() method, we can To export data from a Pandas DataFrame to a CSV ((Comma-Separated Values) file.

Example 1: Write dataframe to csv file

df.to_csv('/Users/Shared/csv/demo1.csv')

 

Example 2: Write dataframe to csv file but not the index

df.to_csv('/Users/Shared/csv/demo2.csv', index=False)

 

Example 3: Write only Name and Age columns to the csv file

df.to_csv('/Users/Shared/csv/demo3.csv', columns=['Name','Age'])

 

Example 4: Write dataframe to csv file with utf-8 encoding

df.to_csv('/Users/Shared/csv/demo4.csv', encoding = 'utf-8')

 

export_to_csv.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, 25, 29, 41, 52, 23],
        'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)
print(df)

# Write dataframe to csv file
df.to_csv('/Users/Shared/csv/demo1.csv')

# Write dataframe to csv file not the index
df.to_csv('/Users/Shared/csv/demo2.csv', index=False)

# Write only Name and Age columns to the csv file
df.to_csv('/Users/Shared/csv/demo3.csv', columns=['Name','Age'])

# Write dataframe to csv file with utf-8 encoding
df.to_csv('/Users/Shared/csv/demo4.csv', encoding = 'utf-8')

 

Output

       Name  Age       City
0   Krishna   34  Bangalore
1       Ram   25    Chennai
2      Joel   29  Hyderabad
3      Gopi   41  Hyderabad
4  Jitendra   52  Bangalore
5       Raj   23    Chennai


demo1.csv 
,Name,Age,City
0,Krishna,34,Bangalore
1,Ram,25,Chennai
2,Joel,29,Hyderabad
3,Gopi,41,Hyderabad
4,Jitendra,52,Bangalore
5,Raj,23,Chennai

demo2.csv 
Name,Age,City
Krishna,34,Bangalore
Ram,25,Chennai
Joel,29,Hyderabad
Gopi,41,Hyderabad
Jitendra,52,Bangalore
Raj,23,Chennai

demo3.csv 
,Name,Age
0,Krishna,34
1,Ram,25
2,Joel,29
3,Gopi,41
4,Jitendra,52
5,Raj,23

demo4.csv 
,Name,Age,City
0,Krishna,34,Bangalore
1,Ram,25,Chennai
2,Joel,29,Hyderabad
3,Gopi,41,Hyderabad
4,Jitendra,52,Bangalore
5,Raj,23,Chennai

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment