Artificial Intelligence

Practical: Import and Export Data between CSV Files and DataFrames (CBSE Class 12 Artificial Intelligence)

Class 12 · Artificial Intelligence

Practical: Import and Export Data between CSV Files and DataFrames

In Artificial Intelligence (AI), Data Science, and Machine Learning (ML), data is one of the most valuable resources. However, data is rarely entered manually into a Python program. Instead, it is usually collected from spreadsheets, databases, online forms, sensors, websites, or cloud platforms. Most of these datasets are stored in CSV (Comma-Separated Values) format because it is lightweight, portable, and supported by almost every software application.

Before any analysis or Machine Learning model can be developed, the dataset must first be imported into Python. After performing cleaning, analysis, or transformation, the processed data is often exported back to a CSV file for future use or sharing. The Pandas library makes this process simple and efficient through the read_csv() and to_csv() functions.

In this practical activity, you will learn how to import a CSV file into a Pandas DataFrame, explore the dataset, perform basic analysis, and export the processed data back into another CSV file.


Practical Aim

To import data from a CSV file into a Pandas DataFrame, analyze the dataset, and export the processed DataFrame into a new CSV file using Python.


Learning Outcomes

After completing this practical, you will be able to:

  • Create and understand CSV files.
  • Import CSV files into a Pandas DataFrame.
  • Display and inspect datasets.
  • Generate statistical summaries of numerical data.
  • Understand DataFrame information.
  • Export processed datasets to CSV files.
  • Prepare datasets for Machine Learning applications.

Software Requirements

Software Purpose
Python 3.x Programming Language
Pandas Library Data Analysis
Google Colab Online Python IDE
Jupyter Notebook Interactive Python Programming
VS Code / PyCharm Desktop Python IDE

Theory

A CSV (Comma-Separated Values) file is a simple text file used to store tabular data. Each line in the file represents one record, while commas separate individual values within that record.

The Pandas library reads CSV files and automatically converts them into a DataFrame, making it easy to analyze, modify, clean, and manipulate the data using Python.

Once the required operations are completed, the DataFrame can be exported back into a CSV file using the to_csv() function.


Sample CSV Dataset

Create a file named student.csv with the following contents:


Name,Class,Marks,City
Aman,XII,91,Jaipur
Neha,XII,88,Delhi
Rahul,XII,95,Mumbai
Priya,XII,84,Udaipur
Rohan,XII,79,Kota

Folder Structure


AI Practical

│

├── student.csv

├── practical.py

└── output.csv

Step 1: Import the Pandas Library

Before working with CSV files, import the Pandas library.


import pandas as pd

The keyword as pd creates an alias, allowing us to write pd.read_csv() instead of pandas.read_csv().


Step 2: Import the CSV File

Use the read_csv() function to read the CSV file.


df = pd.read_csv("student.csv")

The imported data is stored inside the DataFrame named df.


Step 3: Display the Dataset

Print the entire DataFrame.


print(df)

Output


    Name Class  Marks     City

0   Aman   XII     91   Jaipur

1   Neha   XII     88    Delhi

2  Rahul   XII     95   Mumbai

3  Priya   XII     84  Udaipur

4  Rohan   XII     79     Kota

Step 4: Display the First Five Records

Use the head() function to display the first five records.


print(df.head())

If the dataset contains fewer than five rows, all rows are displayed.


Step 5: Display the Last Five Records

Use the tail() function to display the last five records.


print(df.tail())

Step 6: Display Dataset Information

The info() function displays useful information about the dataset.


print(df.info())

The output includes:

  • Total number of rows.
  • Total number of columns.
  • Column names.
  • Data types.
  • Number of non-null values.
  • Memory usage.

Sample Output of info()


<class 'pandas.core.frame.DataFrame'>

RangeIndex: 5 entries, 0 to 4

Data columns (total 4 columns):

Name      object

Class     object

Marks      int64

City       object

memory usage: 292 bytes

Step 7: Generate Statistical Summary

The describe() function generates statistical information for all numerical columns.


print(df.describe())

Output


          Marks

count   5.000000

mean   87.400000

std     6.107373

min    79.000000

25%    84.000000

50%    88.000000

75%    91.000000

max    95.000000

Step 8: Export the DataFrame

After processing the data, export the DataFrame using the to_csv() function.


df.to_csv("output.csv", index=False)

The parameter index=False prevents row numbers from being stored in the exported CSV file.


Understanding index=False

If index=False is not specified, Pandas automatically saves row numbers along with the data.

Without index=False With index=False
Row numbers are saved. Only actual data is saved.
0,Aman,XII,91,Jaipur Aman,XII,91,Jaipur

Flow of Import and Export Process


CSV File

   │

   ▼

read_csv()

   │

   ▼

DataFrame

   │

   ▼

Analysis / Modification

   │

   ▼

to_csv()

   │

   ▼

New CSV File

Complete Program


import pandas as pd

# Step 1: Read CSV File
df = pd.read_csv("student.csv")

# Step 2: Display Complete Dataset
print("Original Dataset")
print(df)

# Step 3: Display First Five Records
print("\nFirst Five Records")
print(df.head())

# Step 4: Display Last Five Records
print("\nLast Five Records")
print(df.tail())

# Step 5: Display Dataset Information
print("\nDataset Information")
print(df.info())

# Step 6: Display Statistical Summary
print("\nStatistical Summary")
print(df.describe())

# Step 7: Display Column Names
print("\nColumn Names")
print(df.columns)

# Step 8: Display Shape
print("\nShape of Dataset")
print(df.shape)

# Step 9: Export DataFrame
df.to_csv("output.csv", index=False)

print("\nData exported successfully.")

Sample Output


Original Dataset

    Name Class  Marks     City
0   Aman   XII     91   Jaipur
1   Neha   XII     88    Delhi
2  Rahul   XII     95   Mumbai
3  Priya   XII     84  Udaipur
4  Rohan   XII     79     Kota

First Five Records

    Name Class  Marks     City
0   Aman   XII     91   Jaipur
1   Neha   XII     88    Delhi
2  Rahul   XII     95   Mumbai
3  Priya   XII     84  Udaipur
4  Rohan   XII     79     Kota

Column Names

Index(['Name', 'Class', 'Marks', 'City'], dtype='object')

Shape of Dataset

(5,4)

Data exported successfully.

Program Explanation

Statement Description
import pandas as pd Imports the Pandas library.
pd.read_csv() Reads data from the CSV file.
head() Displays the first five records.
tail() Displays the last five records.
info() Displays information about the DataFrame.
describe() Displays statistical summary.
columns Displays all column names.
shape Returns the number of rows and columns.
to_csv() Exports the DataFrame into a CSV file.

Dry Run

Step Statement Result
1 Import Pandas Library Loaded
2 Read CSV File DataFrame Created
3 Display Dataset Records Displayed
4 Display Information Dataset Details Shown
5 Generate Statistics Summary Generated
6 Export CSV File output.csv Created

Trace Table

Operation Input Output
Read CSV student.csv DataFrame
Analyze DataFrame Statistics
Export DataFrame output.csv

Observation

  • The CSV file was successfully imported into a DataFrame.
  • The dataset contained five records.
  • The DataFrame functions displayed useful information about the dataset.
  • The processed dataset was exported successfully to a new CSV file.

Expected Result

The CSV dataset is successfully imported into a Pandas DataFrame, analyzed using built-in Pandas functions, and exported to a new CSV file without errors.


Real-Life Applications

  • Importing student examination records.
  • Reading hospital patient information.
  • Importing banking transactions.
  • Analyzing weather data.
  • Reading sales reports.
  • Preparing Machine Learning datasets.
  • Exporting cleaned datasets for future analysis.

Think Like an AI Engineer

An online shopping company receives customer order data every day as a CSV file. Before predicting future sales, what should be the first step after receiving the file?

Click to View Answer

The dataset should first be imported into a Pandas DataFrame using pd.read_csv(). Once imported, it can be inspected, cleaned, analyzed, and prepared for Machine Learning.


Competency-Based Question

A school stores students' examination records in Microsoft Excel. The file is later saved as student.csv. Explain how Python can import this dataset, display the records, and save the processed data into another CSV file.


Common Errors

  • Incorrect file name.
  • Wrong file path.
  • CSV file not uploaded in Google Colab.
  • Forgetting to import the Pandas library.
  • Typing readcsv() instead of read_csv().
  • Misspelling the CSV filename.
  • Not using index=False while exporting.

Troubleshooting Tips

  • Verify that the CSV file exists in the current working directory.
  • Ensure the filename matches exactly.
  • Check that the CSV file is properly formatted.
  • Upload the CSV file before executing the notebook in Google Colab.
  • Install the Pandas library if it is missing.

Best Practices

  • Always preview the dataset using head().
  • Use info() to check data types.
  • Generate statistics using describe() before analysis.
  • Keep the original dataset unchanged and export processed data into a new CSV file.
  • Use meaningful filenames such as student_cleaned.csv or sales_processed.csv.

Viva Questions

  1. What is a CSV file?
  2. Which Pandas function imports a CSV file?
  3. What is a DataFrame?
  4. Which function exports a DataFrame?
  5. Why is index=False used while exporting?
  6. What is the purpose of head()?
  7. What information does info() provide?
  8. Why are CSV files preferred in Artificial Intelligence projects?
  9. Can Microsoft Excel open CSV files?
  10. Name any two applications of CSV files.

Quick Revision

  • read_csv() imports CSV files.
  • to_csv() exports DataFrames.
  • head() displays the first five records.
  • tail() displays the last five records.
  • info() displays DataFrame information.
  • describe() generates statistical summaries.
  • CSV files are widely used in AI and Machine Learning.

Memory Trick

READ → ANALYZE → EXPORT

read_csv() → Import Data
DataFrame → Process Data
to_csv() → Save Data


Exam Tips

  • Remember the syntax of pd.read_csv() and to_csv().
  • Know the purpose of index=False.
  • Understand the functions head(), tail(), info(), and describe().
  • Practice importing datasets in both Google Colab and Python IDE.
  • Always inspect the dataset before exporting it.

Summary

  • CSV files are widely used for storing structured datasets.
  • Pandas imports CSV files using read_csv().
  • Imported data is stored in a DataFrame.
  • DataFrame functions help inspect and analyze datasets.
  • The processed dataset can be exported using to_csv().
  • Importing and exporting datasets is one of the most important practical skills required for Artificial Intelligence and Data Science.