Page 225 - AI_Ver_3.0_class_11
P. 225
Output:
Customer ID First Name Last Name City
0 1 Akash Patel Mumbai
1 2 Priya Sharma Delhi
2 3 Aarav Singh Jaipur
3 4 Neha Trivedi Ahmedabad
4 5 Rahul Mehta Bangalore
5 6 Aishwarya Iyer Chennai
6 7 Rajesh Reddy Hyderabad
7 8 Sneha Gupta Kolkata
8 9 Sanjay Kumar Lucknow
9 10 Deepika Menon Pune
Exporting a DataFrame to a CSV file
The ‘to_csv()’ function in Pandas converts a DataFrame into CSV file format. This function allows you to save the contents
of a DataFrame into a CSV file with various configuration options. You can provide a file object to write the CSV data to
a file; otherwise, the CSV data is returned as a string.
Program 57: To export a DataFrame to a CSV file
# Import pandas library
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Adit', 'Ekam', 'Sakshi', 'Anu'],
'Age':[27, 24, 25, 30],
'Address':['Delhi', 'Kanpur', 'Meerut', 'Indore'],
'Qualification':['M.Sc.', 'MA', 'MCA', 'Ph.D.']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Export the DataFrame to a CSV file
df.to_csv('employee_data.csv', sep=',', index=False)
This code creates a DataFrame from a dictionary containing employee data. It then exports this DataFrame to a CSV file
named 'employee_data.csv'. The parameter 'index=False' is used to exclude the index from being written to the CSV file.
The resulting CSV file will display the data in a tabular format when opened in software like Excel.
Python Programming 223

