Writing CSV Files with Pandas
We can use Pandas to write CSV files. It can done by using pd.DataFrame() function. In this example, the Pandas library is used to convert a list of dictionaries (mydict
) into a DataFrame, representing tabular data. The DataFrame is then written to a Python CSV file named “output.csv” using the to_csv
method, creating a structured and readable data file for further analysis or sharing.
Python3
import pandas as pd mydict = [ { 'branch' : 'COE' , 'cgpa' : '9.0' , 'name' : 'Nikhil' , 'year' : '2' }, { 'branch' : 'COE' , 'cgpa' : '9.1' , 'name' : 'Sanchit' , 'year' : '2' }, { 'branch' : 'IT' , 'cgpa' : '9.3' , 'name' : 'Aditya' , 'year' : '2' }, { 'branch' : 'SE' , 'cgpa' : '9.5' , 'name' : 'Sagar' , 'year' : '1' }, { 'branch' : 'MCE' , 'cgpa' : '7.8' , 'name' : 'Prateek' , 'year' : '3' }, { 'branch' : 'EP' , 'cgpa' : '9.1' , 'name' : 'Sahil' , 'year' : '2' } ] # Create a DataFrame from the list of dictionaries df = pd.DataFrame(mydict) # Write the DataFrame to a CSV file df.to_csv( 'output.csv' , index = False ) |
Output CSV File:
branch,cgpa,name,year
COE,9.0,Nikhil,2
COE,9.1,Sanchit,2
IT,9.3,Aditya,2
SE,9.5,Sagar,1
MCE,7.8,Prateek,3
EP,9.1,Sahil,2
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data.
In article explains What is CSV. Working with CSV files in Python, Reading, and Writing to a CSV file, and Storing Emails in CSV files.
Table of Content
- What is a CSV File?
- Working with CSV files in Python
- Reading a CSV file
- Reading CSV Files Into a Dictionary With csv
- Writing to a CSV file
- Writing a dictionary to a CSV file
- Reading CSV Files With Pandas
- Writing CSV Files with Pandas
- Storing Emails in CSV files
Contact Us