Nexus Learn

Practical 1: Python Toolkit for AI: NumPy, pandas and Matplotlib

Lab Practical CS-511 Artificial Intelligence 12 min read Updated 8 Nov 2026
On this page
  1. 1. Objectives
  2. 2. Word Bank
  3. 3. Background
  4. 4. Time Plan (180 minutes)
  5. Part A - Guided Warm-up (type, run, observe)
  6. Part B - Predict the Output
  7. Part C - Bug Hunt
  8. Part D - Graded Tasks (20 marks)
  9. Part E - Post-Lab Questions
  10. Marking Rubric (applied to Part D)
  11. Submission

1. Objectives

  1. Set up a Python environment for AI work and check library versions.
  2. Create NumPy arrays, use indexing, slicing, broadcasting and vectorised maths (no loops).
  3. Use matrix multiplication (dot product) - the core operation of every neural network.
  4. Load a CSV file with pandas; select, filter, sort, group and add new columns.
  5. Draw and save line, scatter and bar plots with Matplotlib, with title, labels and legend.
  6. Compute a single artificial neuron's output z = X·w + b for many inputs at once.

2. Word Bank

Word

Simple meaning

Real-world example

Library

Ready-made code you import and use

import numpy as np

Array

A grid of numbers of the same type (1-D list, 2-D table)

Marks of 5 students in 3 quizzes

Shape

Size of an array in each direction (rows, columns)

(5, 3) = 5 rows, 3 columns

Vectorised

One operation on the whole array, without a loop

units * 35 for all houses at once

Broadcasting

NumPy stretches a smaller array to match a bigger one

Adding one row of bonus marks to every student

Dot product

Multiply matching numbers and add them up

Bill = units · rates

DataFrame

A pandas table with named columns, like an Excel sheet

bills.csv loaded into df

Boolean mask

An array of True/False used to pick rows

df[df['units'] > 300]

Correlation

A number from -1 to +1 showing how two things move together

Hotter months → more units

Neuron (artificial)

Weighted sum of inputs plus bias, then an activation

Good-yield predictor in Task 5

3. Background

Why these three libraries?

Almost every AI program in Python stands on three libraries. NumPy does fast maths on arrays: a neural network is mostly matrix multiplication, and NumPy does it in one line. pandas reads and cleans tables of data (CSV or Excel files), because AI learns from data. Matplotlib draws graphs, because we must see data and results before we trust them. scikit-learn and scikit-fuzzy, which we use in later labs, are built on NumPy.

Real-world link

A WAPDA/MEPCO bill is units × rate. If you have 1,000 houses, a loop calculates 1,000 bills one by one. NumPy calculates all 1,000 with one line: bills = units * rate. This is called vectorised (whole-array) maths, and it is about 50-100 times faster than a Python loop on large data.

Today's data

Two small files: bills.csv (monthly temperature and electricity units of a house in Burewala) and cotton.csv (10 cotton farms in Burewala, Vehari and Mailsi with area, rain, fertilizer bags and yield in maunds). Type them into Notepad / VS Code exactly as given in the box and save them in the same folder as your notebook.

Data files for this lab

bills.csv

month,avg_temp_c,units

Jan,13,180

Feb,16,170

Mar,22,210

Apr,29,290

May,34,420

Jun,36,510

Jul,33,480

Aug,32,460

Sep,31,400

Oct,26,280

Nov,19,200

Dec,14,190

cotton.csv

farm,district,area_acres,rain_mm,fert_bags,yield_maunds

F01,Burewala,5,310,10,160

F02,Burewala,8,280,14,232

F03,Vehari,4,350,6,96

F04,Vehari,6,300,12,186

F05,Mailsi,7,220,9,161

F06,Mailsi,3,240,4,63

F07,Burewala,10,330,20,330

F08,Vehari,5,260,7,120

F09,Mailsi,6,250,11,168

F10,Burewala,4,290,8,124

4. Time Plan (180 minutes)

Minutes

Activity

Part

0-15

Setup check, create data files

Part A1

15-60

Guided warm-up: NumPy, dot product, pandas, plotting

Part A2-A5

60-75

Predict the output

Part B

75-95

Bug hunt

Part C

95-165

Graded tasks 1-5

Part D

165-180

Post-lab questions, lab book entry, submission

Part E

Part A - Guided Warm-up (type, run, observe)

A1. Setup check

Install once: pip install numpy pandas matplotlib (Anaconda already has them). Then run this cell. Your version numbers may be different - any NumPy 1.26+ and pandas 2.0+ is fine.

import sys, numpy as np, pandas as pd, matplotlib

print("Python ", sys.version.split()[0])

print("NumPy ", np.__version__)

print("pandas ", pd.__version__)

print("Matplotlib", matplotlib.__version__)

Output

Python 3.13.16

NumPy 2.5.3

pandas 3.0.5

Matplotlib 3.11.2

A2. Arrays and vectorised maths

Five houses on one street used these units last month. The rate is Rs 35 per unit. Compare the loop with the one-line NumPy version - both give the same bills.

import numpy as np

units = np.array([120, 250, 310, 95, 480])

print("Units :", units)

print("Shape :", units.shape, " Type:", units.dtype)

# loop way

bills_loop = []

for u in units:

bills_loop.append(int(u * 35))

print("Loop :", bills_loop)

# vectorised way (no loop)

bills = units * 35

print("NumPy :", bills)

print("Total Rs", bills.sum(), "| Average Rs", bills.mean(), "| Highest Rs", bills.max())

print("Houses above 300 units:", units[units > 300])

Output

Units : [120 250 310 95 480]

Shape : (5,) Type: int64

Loop : [4200, 8750, 10850, 3325, 16800]

NumPy : [ 4200 8750 10850 3325 16800]

Total Rs 43925 | Average Rs 8785.0 | Highest Rs 16800

Houses above 300 units: [310 480]

A3. 2-D arrays and the dot product

A 2-D array is a table. The dot product multiplies matching numbers and adds them. Here each row is a student, each column a quiz; the weights say how much each quiz counts. One @ (matrix multiply) gives every student's weighted score.

import numpy as np

marks = np.array([[8, 7, 9],

[5, 6, 4],

[9, 9, 10],

[6, 8, 7]])

weights = np.array([0.2, 0.3, 0.5]) # quiz 3 counts most

print("Shape of marks :", marks.shape)

print("Student 2 marks :", marks[1])

print("Quiz 3 column :", marks[:, 2])

weighted = marks @ weights # same as np.dot(marks, weights)

print("Weighted scores :", weighted.round(2))

print("By hand, student 1: 8*0.2 + 7*0.3 + 9*0.5 =", round(8*0.2 + 7*0.3 + 9*0.5, 2))

Output

Shape of marks : (4, 3)

Student 2 marks : [5 6 4]

Quiz 3 column : [ 9 4 10 7]

Weighted scores : [8.2 4.8 9.5 7.1]

By hand, student 1: 8*0.2 + 7*0.3 + 9*0.5 = 8.2

A4. pandas: load, look, filter, sort

pandas reads the CSV into a DataFrame (a table). Each column has a name, so we write df['units'] instead of remembering column numbers.

import pandas as pd

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

print(df.head(3))

print("Rows, columns:", df.shape)

print("Average units:", round(df["units"].mean(), 1))

hot = df[df["avg_temp_c"] >= 30]

print("Hot months:", list(hot["month"]))

print(df.sort_values("units", ascending=False).head(3))

Output

month avg_temp_c units

0 Jan 13 180

1 Feb 16 170

2 Mar 22 210

Rows, columns: (12, 3)

Average units: 315.8

Hot months: ['May', 'Jun', 'Jul', 'Aug', 'Sep']

month avg_temp_c units

5 Jun 36 510

6 Jul 33 480

7 Aug 32 460

A5. Matplotlib: line plot saved to a file

Always give a plot a title, axis labels with units, and save it with savefig BEFORE plt.show().

import pandas as pd

import matplotlib.pyplot as plt

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

plt.figure(figsize=(7, 3.5))

plt.plot(df["month"], df["units"], marker="o", label="Units used")

plt.title("Monthly electricity use - house in Burewala")

plt.xlabel("Month"); plt.ylabel("Units (kWh)")

plt.grid(alpha=0.3); plt.legend()

plt.tight_layout()

plt.savefig("bills_plot.png", dpi=100)

print("Saved bills_plot.png")

Output

Saved bills_plot.png

Part B - Predict the Output

Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.

B1.

import numpy as np

a = np.arange(1, 7)

print(a.reshape(2, 3))

print(a.reshape(2, 3).shape)

My prediction

B2.

import numpy as np

a = np.array([10, 20, 30, 40, 50])

print(a[1:4], a[-1], a[::2])

My prediction

B3.

import numpy as np

m = np.array([[1, 2], [3, 4]])

print(m * 10)

print(m + np.array([100, 200]))

My prediction

B4.

import numpy as np

t = np.array([28, 36, 41, 33, 39])

print(t[t > 35])

print((t > 35).sum())

My prediction

B5.

import numpy as np

m = np.array([[2, 4], [6, 8]])

print(m.sum(), m.sum(axis=0), m.sum(axis=1), m.mean())

My prediction

Part C - Bug Hunt

Each program has ONE bug. Some crash with an error message; others run but give a wrong answer (silent logic error - the dangerous kind). Find the bug, explain it and write the fix.

C1.

import numpy as np

a = np.array([1, 2, 3])

b = np.array([4, 5])

print(a + b)

Bug, why it happens, and the fixed line(s)

C2.

import pandas as pd

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

print(df["Units"].max())

Bug, why it happens, and the fixed line(s)

C3.

import pandas as pd

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

print(df[df["units"] > 300 and df["avg_temp_c"] > 33])

Bug, why it happens, and the fixed line(s)

C4.

import numpy as np

temps = np.array([30, 32, 35])

backup = temps # keep the original safe

temps[0] = 99

print("backup:", backup) # we expect [30 32 35]

It runs and prints

backup: [99 32 35]

Bug, why it happens, and the fixed line(s)

C5.

import numpy as np

marks = np.array([[8, 7, 9], [5, 6, 4], [9, 9, 10], [6, 8, 7]])

quiz_avg = marks.mean(axis=1) # average of each quiz

print("Quiz averages:", quiz_avg)

It runs and prints

Quiz averages: [8. 5. 9.33333333 7. ]

Bug, why it happens, and the fixed line(s)

Part D - Graded Tasks (20 marks)

Task

Level

Title

Marks

T1

Easy

Weekly temperature report

3

T2

Medium

Quiz marks analysis

4

T3

Medium

Electricity bills with pandas

4

T4

Medium

Plotting the bills

4

T5

Challenge

One artificial neuron (preview of Practical 2)

5

Total

20

Task 1 (Easy, 3 marks): Weekly temperature report

The maximum temperatures (°C) in Burewala for one week in June were 38, 41, 43, 40, 36, 44, 42. Store them in a NumPy array and print: the highest, the lowest, the average (1 decimal), how many days were above 40 °C, and which day numbers (1-7) were above 40 °C. Use NumPy functions, no loops.

Sample run (your output must match):

Output

Highest : 44

Lowest : 36

Average : 40.6

Days above 40: 4

Day numbers : [2 3 6 7]

Your code (or attach the file)

Task 2 (Medium, 4 marks): Quiz marks analysis

Marks (out of 10) of 5 students in 3 quizzes are: Ali [7, 8, 6], Sana [9, 9, 10], Bilal [4, 6, 5], Hira [8, 7, 9], Usman [6, 5, 7]. Store them in a 5×3 array. Print (a) each student's total, (b) the average of each quiz (2 decimals), (c) the name of the top student (use argmax), and (d) the marks scaled to 0-1 with min-max scaling: (x - min) / (max - min) of the whole array, rounded to 2 decimals.

Sample run (your output must match):

Output

Totals : [21 28 15 24 18]

Quiz average: [6.8 7. 7.4]

Top student : Sana

Scaled 0-1:

[[0.5 0.67 0.33]

[0.83 0.83 1. ]

[0. 0.33 0.17]

[0.67 0.5 0.83]

[0.33 0.17 0.5 ]]

Your code (or attach the file)

Task 3 (Medium, 4 marks): Electricity bills with pandas

Load bills.csv. (a) Add a column 'bill' using a simple slab tariff: Rs 22 per unit if units ≤ 200, otherwise Rs 35 per unit for ALL units (use np.where). (b) Print the months with units above 400 and their bills. (c) Add a 'season' column: 'Summer' for Apr-Sep, else 'Winter', and print the average units of each season with groupby. (d) Print the total yearly bill.

Sample run (your output must match):

Output

month units bill

4 May 420 14700

5 Jun 510 17850

6 Jul 480 16800

7 Aug 460 16100

season

Summer 426.7

Winter 205.0

Name: units, dtype: float64

Yearly bill Rs 123030

Your code (or attach the file)

Task 4 (Medium, 4 marks): Plotting the bills

Using bills.csv, make ONE figure with two side-by-side plots (plt.subplots(1, 2)): left - a bar chart of units per month; right - a scatter plot of avg_temp_c (x) against units (y). Give each plot a title and axis labels, save the figure as task4.png, and print the correlation between temperature and units (df['avg_temp_c'].corr(df['units']), 3 decimals). In one line, explain what the correlation means.

Sample run (your output must match):

Output

Saved task4.png

Correlation: 0.937

Strong positive: hotter months use more electricity (fans and ACs).

Your code (or attach the file)

Task 5 (Challenge, 5 marks): One artificial neuron (preview of Practical 2)

Load cotton.csv. Make two input features for each farm: x1 = fert_bags / area_acres (bags per acre) and x2 = rain_mm / 100. Stack them into a 10×2 array X. Label a farm 'good' (1) if yield per acre ≥ 28 maunds, else 0. A neuron with weights w = [1.5, 0.5] and bias b = -4.5 computes z = X @ w + b and predicts 1 if z ≥ 0 (step activation). (a) Print z (3 decimals), predictions and true labels. (b) Print the accuracy. (c) Print the farm names it got wrong. (d) Try w = [2.0, 0.5], b = -5.2 and print the new accuracy. No loops are allowed.

Sample run (your output must match):

Output

z : [ 0.05 -0.475 -0.5 0. -1.471 -1.3 0.15 -1.1 -0.5 -0.05 ]

pred : [1 0 0 1 0 0 1 0 0 0]

true : [1 1 0 1 0 0 1 0 1 1]

Accuracy: 0.7

Wrong farms: ['F02', 'F09', 'F10']

New accuracy: 0.8

Your code (or attach the file)

Part E - Post-Lab Questions

E1. Why is vectorised NumPy code preferred over Python loops in AI programs?

Your answer

E2. What is the difference between axis=0 and axis=1 in a 2-D array? Give an example from Task 2.

Your answer

E3. Write the formula a single artificial neuron uses, and name each part.

Your answer

E4. Why should you save a figure before calling plt.show()?

Your answer

E5. Task 4 found a correlation of 0.937 between temperature and units. Does heat CAUSE the units? Explain.

Your answer

Marking Rubric (applied to Part D)

Criterion

Full

Partial

None

Code runs without errors

Runs fully

Small fixable error

Does not run

Correct output

All parts match

Most parts

Few or none

Uses NumPy/pandas properly (no loops where asked)

Vectorised throughout

Some loops

Loops everywhere

Plots: title, labels, saved file

All present

Some missing

No plot

Code style: names and comments

Clear

Partly clear

Unclear

Submission

  • Make a folder RollNo_P01 (e.g. 2023-ag-1234_P01) with task1.py ... task5.py (or one notebook P01.ipynb), bills.csv, cotton.csv and task4.png.
  • Zip the folder and upload it to the LMS / class Google Classroom by the end of the lab day.
  • Copy Task 2 and Task 5 code and output into your Lab Book (Practical 1 pages) for the instructor's signature next week.
  • Copied code from another student gets zero for both students. Using AI tools to explain errors is allowed; say so in a comment.

← All CS-511 material