0% found this document useful (0 votes)
3 views21 pages

Unit1 Python Notes Worksheets

Uploaded by

chaturyareddy215
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Unit1 Python Notes Worksheets

Uploaded by

chaturyareddy215
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ARTIFICIAL INTELLIGENCE | CLASS XII

UNIT 1: PYTHON PROGRAMMING — II


Detailed Student Notes • Worksheets • 6 Practical Questions

Learning Objectives
1. Review and apply the NumPy and Pandas libraries for data manipulation.
2. Import and export data between CSV files and Pandas DataFrames.
3. Handle missing values using dropna() and fillna() strategies.
4. Understand and implement the Linear Regression algorithm.
5. Perform Exploratory Data Analysis (EDA) on real-world datasets.

Topics at a Glance
1.1 Python Libraries — NumPy & Pandas
1.2 Pandas Data Structures — Series & DataFrame
1.3 Import / Export CSV Files with Pandas
1.4 Handling Missing Values
1.5 Case Study — Student Marks Dataset
1.6 Practical Activity — Linear Regression (Advanced Learners)

-1-
1.1 Python Libraries
Python libraries are collections of pre-written code that help us perform common tasks without
writing everything from scratch. They act as toolkits providing ready-made functions and methods.
In Data Science and Artificial Intelligence, two essential libraries are:
• NumPy — for numerical computing and array operations
• Pandas — for data manipulation and analysis

1.1.1 NumPy — Numerical Python


NumPy provides support for large multi-dimensional arrays and matrices, along with a wide
collection of mathematical functions.
Key Terms:
• ndarray: The core N-dimensional array object in NumPy
• Rank: The number of dimensions (axes) of the array
• Shape: A tuple giving the size along each dimension, e.g. (3, 4)

Creating NumPy Arrays:


import numpy as np

# 1D Array
arr1 = [Link]([10, 20, 30, 40])
print(arr1) # [10 20 30 40]
print([Link]) # 1 (rank = 1)

# 2D Array
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # (2, 3) -> 2 rows, 3 columns
print([Link]) # 2

# Array of zeros / ones


zeros = [Link]((3, 3))
ones = [Link]((2, 4))
print(zeros)

1.1.2 Pandas Library


Pandas is built on top of NumPy and provides high-level data structures for working with
structured/tabular data. It is used for loading datasets, cleaning data, and performing complex
analysis.
Pandas provides two primary data structures:
• Series — one-dimensional labeled array
• DataFrame — two-dimensional table with labeled rows and columns

A. Series
A Series is a one-dimensional labeled array that can hold any data type.
import pandas as pd

# From a list
marks = [Link]([90, 85, 92, 78])

-2-
print(marks)

# From a dictionary
data = {'Maths': 95, 'Science': 88, 'English': 76}
s = [Link](data)
print(s)

B. DataFrame
A DataFrame is a 2D table with labeled rows and columns — similar to a spreadsheet.

i) From NumPy arrays:


import numpy as np
import pandas as pd

array1 = [Link]([90, 100, 110, 120])


array2 = [Link]([50, 60, 70, 80])
array3 = [Link]([10, 20, 30, 40])

marksDF = [Link]([array1, array2, array3],


columns=['A', 'B', 'C', 'D'])
print(marksDF)

ii) From a dictionary of lists:


import pandas as pd

data = {'Name': ['Varun', 'Ganesh', 'Joseph', 'Abdul', 'Reena'],


'Age': [37, 30, 38, 39, 40]}

df = [Link](data)
print(df)

# Output:
# Name Age
# 0 Varun 37
# 1 Ganesh 30
# 2 Joseph 38
# 3 Abdul 39
# 4 Reena 40

iii) From a list of dictionaries:


listDict = [{'a': 10, 'b': 20}, {'a': 5, 'b': 10, 'c': 20}]
df = [Link](listDict)
print(df)

# Output:
# a b c
# 0 10 20 NaN
# 1 5 10 20.0
# (Missing value becomes NaN automatically)

-3-
[Link] Adding and Deleting Rows / Columns
Adding a new column:
# Existing DataFrame - Result
ResultSheet = {
'Rajat': [Link]([90, 91, 97], index=['Maths','Science','Hindi']),
'Amrita': [Link]([92, 81, 96], index=['Maths','Science','Hindi']),
'Meenakshi': [Link]([89, 91, 88], index=['Maths','Science','Hindi'])
}
Result = [Link](ResultSheet)

# Add column for 'Fathima'


Result['Fathima'] = [89, 78, 76]
print(Result)

Adding a new row using .loc[]:


[Link]['English'] = [90, 92, 89, 80]
print(Result)

# Modify an existing row


[Link]['Science'] = [92, 84, 90, 72]
print(Result)

Deleting rows and columns using drop():


# Delete a row (axis=0)
Result = [Link]('Hindi', axis=0)

# Delete multiple columns (axis=1)


Result = [Link](['Rajat', 'Meenakshi'], axis=1)
print(Result)

[Link] Important DataFrame Attributes


Attribute Description Example
[Link] Row labels RangeIndex(start=0, stop=4)
[Link] Column names list Index(['Name','Marks','Sports'])
[Link] Rows × Columns tuple (4, 3)
[Link](n) First n rows [Link](2) shows rows 0 & 1
[Link](n) Last n rows [Link](2) shows last 2 rows
[Link] Data types of columns Name: object, Marks: int64
[Link]() Summary statistics count, mean, std, min, max

import pandas as pd

dict_data = {
'Student': [Link](['Arnav','Neha','Priya','Rahul'],
index=['Data 1','Data 2','Data 3','Data 4']),
'Marks': [Link]([85, 92, 78, 83],

-4-
index=['Data 1','Data 2','Data 3','Data 4']),
'Sports': [Link](['Cricket','Volleyball','Hockey','Badminton'],
index=['Data 1','Data 2','Data 3','Data 4'])
}
df = [Link](dict_data)

print([Link]) # Index(['Data 1','Data 2','Data 3','Data 4'])


print([Link]) # Index(['Student','Marks','Sports'])
print([Link]) # (4, 3)
print([Link](2)) # First 2 rows
print([Link]())# Summary statistics

-5-
1.2 Import and Export — CSV Files and DataFrames
CSV (Comma-Separated Values) files store tabular data as plain text. Each line represents a row;
values are separated by commas. They are widely used because they are simple, portable, and
compatible with most tools.

1.2.1 Importing a CSV File — pd.read_csv()


import pandas as pd

# Basic import
df = pd.read_csv('[Link]')
print(df)

# Import with full path (Python IDE / Anaconda)


df = pd.read_csv('C:/PANDAS/[Link]', sep=',', header=0)
print(df)

# Useful optional parameters:


# sep = delimiter character (default ',')
# header = row number of column names (default 0 = first row)
# index_col = column to use as row labels
# nrows = how many rows to read

1.2.2 Exporting a DataFrame — df.to_csv()


# Export to CSV — Python IDE
df.to_csv('C:/PANDAS/[Link]', sep=',')

# Export on Google Colab


df.to_csv('[Link]', index=False) # index=False removes row numbers

# The exported file will contain column headers and all data rows.

Uploading a CSV in Google Colab — Step by Step


Step 1: Open [Link] and create a new notebook.
Step 2: Click the folder icon on the left sidebar.
Step 3: Click the Upload button (arrow pointing up) and choose your CSV file.
Step 4: After upload completes, use pd.read_csv('[Link]') in your code cell.

-6-
1.3 Handling Missing Values
Real-world datasets almost always contain missing values. Pandas represents them as NaN (Not a
Number). There are two main strategies:

Strategy 1: Drop the Row Strategy 2: Fill / Estimate

Remove entire rows containing NaN. Replace NaN with a value: 0, mean, median,
Reduces dataset size. Best when missing or a nearby value. Preserves dataset size.
data is few. Function: [Link](value)
Function: [Link]()

1.3.1 Checking — isnull()


import pandas as pd
import numpy as np

ResultSheet = {
'Maths': [Link]([90, 91, 97, 89, 65, 93],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'Science': [Link]([92, 81, [Link], 87, 50, 88],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'Hindi': [Link]([81, 71, 67, 82, [Link], 89],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'AI': [Link]([94, 95, 99, [Link], 96, 99],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet'])
}
marks = [Link](ResultSheet)

print([Link]()) # Full True/False matrix


print(marks['Science'].isnull().any()) # True - Science has NaN
print([Link]().sum()) # NaN count per column
print([Link]().sum().sum()) # Total NaN = 3

1.3.2 Dropping — dropna()


clean = [Link]()
print(clean)
# Rows for Meera, Joseph, Suhana are removed
# (each had one missing value)

1.3.3 Filling — fillna()


# Replace NaN with 0
filled_zero = [Link](0)
print(filled_zero)

# Replace NaN with column mean (best practice)


filled_mean = [Link]([Link]())
print(filled_mean)

# Replace NaN with 50 (e.g., passing marks)


filled_custom = [Link](50)

-7-
print(filled_custom)

-8-
1.4 Case Study — Student Marks Dataset
Scenario: A class result sheet has missing values because students missed exams due to illness.
Meera missed Science, Suhana missed Hindi, and Joseph missed AI.

Complete Demonstration Code:


import pandas as pd
import numpy as np

ResultSheet = {
'Maths': [Link]([90,91,97,89,65,93],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'Science': [Link]([92,81,[Link],87,50,88],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'English': [Link]([89,91,88,78,77,82],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'Hindi': [Link]([81,71,67,82,[Link],89],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet']),
'AI': [Link]([94,95,99,[Link],96,99],
index=['Heena','Shefali','Meera','Joseph','Suhana','Bismeet'])
}
marks = [Link](ResultSheet)

print('=== Original Data ===')


print(marks)

print('\n=== Missing Value Matrix ===')


print([Link]())

print('\n=== Total NaN per column ===')


print([Link]().sum())

print('\n=== After dropna() ===')


print([Link]())

print('\n=== After fillna(0) ===')


print([Link](0))

print('\n=== After fillna(mean) ===')


print([Link]([Link]().round(1)))

-9-
1.5 Practical Activity — Linear Regression (Advanced)
Linear Regression is a supervised machine learning algorithm used to predict a continuous output
variable based on one or more input features. It fits a best-fit straight line through the data.

Key Formula
y = mX + c
y = predicted output value (e.g., house price)
X = input feature(s) (e.g., area, number of rooms)
m = slope (how much y changes per unit of X)
c = y-intercept (value of y when X = 0)
The algorithm learns optimal values of m and c from the training data.

Complete Implementation with USA Housing Dataset:


import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Step 1: Load data


df = pd.read_csv('USA_Housing.csv')
print([Link]())
print([Link]) # (5000, 7)

# Step 2: EDA
print([Link]()) # Summary statistics
print([Link]().sum()) # No missing values expected

# Step 3: Define features (X) and target (y)


X = df[['Avg. Area Income', 'Avg. Area House Age',
'Avg. Area Number of Rooms', 'Area Population']]
y = df['Price']

# Step 4: Train-test split (80% train, 20% test)


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)

print('Training rows:', X_train.shape[0]) # ~4000


print('Testing rows: ', X_test.shape[0]) # ~1000

# Step 5: Train the model


model = LinearRegression()
[Link](X_train, y_train)

# Step 6: Predict on test data


predictions = [Link](X_test)

# Step 7: Compare actual vs predicted


comparison = [Link]({
'Actual': y_test[:5].values,
'Predicted': predictions[:5].round(2)
})
print(comparison)

# Note: Model evaluation (MAE, R2 score) is covered in the next chapter.

- 10 -
Important Terms
Training Set — 80% of data; used to fit (train) the model.
Testing Set — 20% of data; used to evaluate model performance.
Prediction — The output value estimated by the trained model.
Error — The difference between actual and predicted values.
random_state — Seed for reproducibility; same split each run.

- 11 -
WORKSHEET 1
NumPy & Pandas — Series and DataFrame
Name: _______________________ Class: XII Roll No: _______ Date: ___________

Section A — Multiple Choice Questions (Circle the correct option)

Q1. Which of the following is NOT a primary data structure in Pandas?


a) Series
b) DataFrame
c) ndarray
d) Both a and b are Pandas structures
Answer: _______

Q2. [Link] for a DataFrame with 4 rows and 3 columns returns:


a) [4, 3]
b) (3, 4)
c) (4, 3)
d) 12
Answer: _______

Q3. Which method displays the first 3 rows of a DataFrame?


a) [Link](3)
b) [Link](3)
c) [Link](3)
d) [Link](3)
Answer: _______

Q4. To delete a column, which axis value is used in drop()?


a) axis=0
b) axis=1
c) axis=2
d) axis='col'
Answer: _______

Section B — Fill in the Blanks

1. The _______________ attribute of a DataFrame returns the column names.

2. To add a new row to a DataFrame, we use the _______________ method.

3. A _______________ is a one-dimensional labeled array in Pandas.

4. In NumPy, the number of dimensions of an array is called its _______________.

- 12 -
5. Dictionary keys become _______________ labels in a Pandas DataFrame by default.

Section C — Predict the Output

Q1. What will the following code output? Write your answer below.

import pandas as pd
data = {'Fruit': ['Apple','Mango','Banana'], 'Price': [50, 30, 20]}
df = [Link](data)
print([Link])
print([Link])

Q2. What will [Link](2) print for the DataFrame created in the above code?

Section D — Write the Code

Q3. Write Python code to create a DataFrame for students 'Ravi', 'Priya', 'Sam' with
marks 88, 92, 75. Print the DataFrame and its shape.

- 13 -
Q4. A DataFrame 'Result' has columns Maths, Science, English. Write code to: (a) add a
new row for 'Hindi' with marks [85, 78, 90], and (b) delete the 'Science' column.

- 14 -
WORKSHEET 2
CSV Import / Export & Handling Missing Values
Name: _______________________ Class: XII Roll No: _______ Date: ___________

Section A — Multiple Choice Questions

Q1. Which function reads a CSV file into a Pandas DataFrame?


a) [Link]('[Link]')
b) pd.read_csv('[Link]')
c) pandas.read_file('[Link]')
d) pd.open_csv('[Link]')
Answer: _______

Q2. What does fillna(0) do?


a) Removes rows with missing values
b) Fills all NaN with zeros
c) Returns a count of missing values
d) Converts all data to NaN
Answer: _______

Q3. isnull() returns __________ when a value is missing.


a) 0
b) None
c) True
d) NaN
Answer: _______

Q4. Which parameter prevents row numbers from being written to a CSV?
a) header=False
b) sep=False
c) index=False
d) rows=False
Answer: _______

Section B — True or False

1. dropna() removes columns with missing values. [ True / False ]

2. pd.read_csv() can accept a full file path as its argument. [ True / False ]

3. Missing values in Pandas are represented as NaN. [ True / False ]

4. isnull().sum().sum() gives the total number of NaN in a DataFrame. [ True / False ]

- 15 -
Section C — Write the Code

Q1. A CSV file '[Link]' has columns: Product, Quantity, Price. Write Python code to:
(a) Load the file, (b) Check for missing values, (c) Fill NaN with 0, (d) Export to
'sales_clean.csv' without the index.

Q2. The following student data has NaN values. Write complete Python code to create
this DataFrame, display missing values, then fill NaN with the column mean: Amir:
Maths=85, Science=NaN, English=78 Binya: Maths=NaN, Science=90, English=82
Chandni: Maths=72, Science=65, English=NaN

- 16 -
- 17 -
PRACTICAL EXAMINATION QUESTIONS
Unit 1: Python Programming — II | Six Lab Questions
Attempt any FOUR. All questions carry equal marks.

Instructions
Use Google Colab or Python IDE (Anaconda / IDLE) for coding.
Save your work as: Practical_YourName_Q#.ipynb or .py
Include comments in your code to explain each step.
Print the output after each major operation.
Dataset links are provided where required.

PRACTICAL QUESTION 1
Topic: DataFrame Creation and Manipulation
Create a Pandas DataFrame for a school result sheet of 6 students with subjects:
Maths, Science, English, Hindi, Computer Science. Perform the following operations:
1. Create the DataFrame using a dictionary of Pandas Series with student names
as the index.
2. Display the shape, column names, and index of the DataFrame.
3. Add a new subject column 'Physical Education' with marks for all 6 students.
4. Delete the 'Hindi' row using the drop() method.
5. Use [Link](3) and [Link](2) to display parts of the DataFrame.
6. Display [Link]() and explain what each statistic means.
Hint: Use [Link]([...], index=['Stu1','Stu2',...]) for each column.

PRACTICAL QUESTION 2
Topic: CSV Import, Export and Data Exploration
Create a CSV file named 'student_data.csv' with columns: Name, Age, Grade, City,
Score (minimum 8 rows). Write a program to:
7. Load the CSV into a Pandas DataFrame and display it with print().
8. Display summary statistics using describe().
9. Add a new column 'Pass_Fail': value is 'Pass' if Score >= 40, else 'Fail'.
10. Export the updated DataFrame to 'student_result.csv' without the index column.
11. Verify the exported file by reading it back and displaying it.
Hint: df['Pass_Fail'] = df['Score'].apply(lambda x: 'Pass' if x >= 40
else 'Fail')

- 18 -
PRACTICAL QUESTION 3
Topic: Handling Missing Values — Complete Pipeline
A hospital records patient data. Some readings are missing. Create the following
DataFrame (use [Link] for missing values) and perform all operations listed:
12. Create the DataFrame: Name={Arjun,Bhavna,Chitra,Dev,Esha,Farhan},
Age={34,NaN,28,45,NaN,52}, BP={120,130,NaN,110,125,NaN},
Sugar={NaN,90,85,NaN,78,95}, Temperature={98.6,99.1,98.9,NaN,97.8,98.5}.
13. Use isnull() to display the full missing-value Boolean matrix.
14. Count missing values per column using isnull().sum() and total using
isnull().sum().sum().
15. Create DataFrame 'df_filled' by replacing all NaN with the column mean (rounded
to 1 decimal).
16. Create DataFrame 'df_dropped' by removing all rows with any missing value.
17. Print both DataFrames and state which method retained more data and why.
Hint: [Link]([Link]().round(1)) replaces each NaN with its column
mean.

PRACTICAL QUESTION 4
Topic: NumPy Arrays and DataFrame Integration
Write a Python program to demonstrate the use of NumPy arrays in creating
DataFrames:
18. Create four NumPy arrays: Term1, Term2, Term3, and Final_Exam marks for 5
students.
19. Create a DataFrame from these arrays with student names as the index and
exam names as columns.
20. Add a 'Total' column = sum of all four exams.
21. Add an 'Average' column = mean of the four exams (rounded to 1 decimal).
22. Display shape, dtypes, index, and columns attributes.
23. Export the final DataFrame to 'exam_results.csv' (index=True so student names
are saved).
Hint: [Link]([90,85,88,92,79]) creates a 1D array of marks.

- 19 -
PRACTICAL QUESTION 5
Topic: Sales Data Analysis — End-to-End Pipeline
Create a CSV file 'monthly_sales.csv' with columns: Month, Product, Units_Sold,
Price_Per_Unit (at least 12 rows, include 2-3 NaN values intentionally). Write a complete
program that:
24. Loads the CSV file into a DataFrame and displays it.
25. Identifies and prints the count of missing values per column.
26. Fills NaN in 'Units_Sold' with 0 and NaN in 'Price_Per_Unit' with the column
mean.
27. Adds a column 'Revenue' = Units_Sold * Price_Per_Unit.
28. Finds total revenue per product using: [Link]('Product')['Revenue'].sum()
29. Exports the final DataFrame (with Revenue column) to 'sales_report.csv'.
30. BONUS: Print which product had the highest total revenue.
Hint: [Link]('Product')['Revenue'].sum().idxmax() returns the top
product.

PRACTICAL QUESTION 6
Topic: Linear Regression — House Price Prediction (Advanced)
Using the USA Housing dataset, implement a complete Linear Regression pipeline.
Download from the class shared link:
[Link]
31. Load the dataset into a DataFrame. Display the first 5 rows and the shape.
32. Perform EDA: print describe(), check for missing values, print column names.
33. Select feature columns (X) and set target column y = df['Price'].
34. Split the data: 80% training and 20% testing using
train_test_split(random_state=42).
35. Create and train a LinearRegression model using X_train and y_train.
36. Predict house prices on X_test. Display a table of Actual vs Predicted for the first
10 rows.
37. Calculate and print Mean Absolute Error (MAE) and comment on model
accuracy.
Hint: from [Link] import mean_absolute_error | mae =
mean_absolute_error(y_test, predictions)

- 20 -
Quick Reference Sheet — Unit 1
Function / Attribute What it Does
pd.read_csv('[Link]') Load CSV into DataFrame
df.to_csv('[Link]', Export DataFrame to CSV (no row numbers)
index=False)
[Link] Returns (rows, columns) as a tuple
[Link](n) First n rows (default 5)
[Link](n) Last n rows (default 5)
[Link] List of column names
[Link] Row labels / index
[Link] Data type of each column
[Link]() Summary statistics (count, mean, std, min, max)
[Link]() True/False matrix — True where value is NaN
[Link]().sum() Count of NaN per column
[Link]().sum().sum() Total NaN count in entire DataFrame
[Link]() Remove all rows containing at least one NaN
[Link](value) Replace all NaN with a specified value
[Link]([Link]()) Replace NaN with column mean
[Link]('col', axis=1) Delete a column
[Link]('row', axis=0) Delete a row
[Link]['label'] Access a row by its label
[Link]['label'] = [...] Add or update a row
df['NewCol'] = [...] Add a new column
[Link] NumPy missing value constant
train_test_split(X, y, Split data 80% train / 20% test
test_size=0.2)
[Link](X_train, Train the Linear Regression model
y_train)
[Link](X_test) Generate predictions on test data

AI Class XII — Unit 1: Python Programming-II | CBSE Subject Code: 843

- 21 -

You might also like