Page 212 - Touhpad Ai
P. 212
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 20: 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.
21 st
VIDEO SESSION Century #Digital Literacy
Skills
Scan the QR code or visit the following link to watch the videos:
NumPy for Beginners in 15 minutes
https://www.youtube.com/watch?v=uRsE5WGiKWo
Pandas for Data Science in 20 Minutes
https://www.youtube.com/watch?v=tRKeLrwfUgU
After watching the videos, answer the following question:
Write one key difference between NumPy and Pandas.
Data Cleaning Techniques with Pandas
In the previous chapter, you learnt data cleaning techniques using MS Excel. Let us now learn these techniques in
Python. When working with data in Python, we often use a powerful library called Pandas. It helps us store, view,
and clean data easily using DataFrames (tables of rows and columns). Real-world data is rarely perfect—it may have
missing values, duplicates, wrong formats, or extra spaces. To make our data clean and ready for use, we apply some
simple data cleaning techniques using Pandas.
210 Touchpad Artificial Intelligence - XI

