Programming for AI – Lab Manual (NumPy, Pandas, Matplotlib)
1. NumPy
1. Arrays & Basic Operations
Theory:
NumPy is a Python library for handling numerical computations efficiently. It provides arrays
(ndarrays) that are faster and more powerful than Python lists.
Code Example:
import numpy as np
# Create arrays
arr = [Link]([1, 2, 3, 4, 5])
matrix = [Link]([[1, 2], [3, 4]])
# Basic operations
print("Array:", arr)
print("Matrix:", matrix)
print("Mean of arr:", [Link](arr))
print("Max in matrix:", [Link](matrix))
print("Element-wise addition:", arr + 10)
2. Indexing, Broadcasting, Random Numbers
Theory:
NumPy allows slicing of arrays, broadcasting operations across shapes, and generating random
numbers. These features are essential in AI for data preprocessing and simulations.
Code Example:
# Slicing
arr = [Link](1, 11) # [1,2,...,10]
print("Slice [2:7]:", arr[2:7])
# Broadcasting
A = [Link]([1, 2, 3])
B = [Link]([4])
print("Broadcasting:", A + B)
# Random numbers
rand_mat = [Link](3, 3) # 3x3 random matrix
print("Random Matrix:\n", rand_mat)
[Link] Algebra & Statistics
Theory:
NumPy provides functions for linear algebra such as matrix multiplication, eigenvalues, and
inversion, which are widely used in AI models.
Code Example:
# Matrix multiplication & linear algebra
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[2, 0], [1, 2]])
print("Dot Product:\n", [Link](A, B))
print("Inverse of A:\n", [Link](A))
print("Eigenvalues of A:", [Link](A))
2. Pandas
1. Series & DataFrames
Theory:
Pandas is used for data handling in tabular form. A DataFrame is like a spreadsheet, making it
ideal for AI data analysis.
Code Example:
import pandas as pd
# Create DataFrame
data = {'Name': ['Ali', 'Sara', 'John'],
'Age': [22, 25, 29],
'Score': [85, 90, 78]}
df = [Link](data)
print(df)
print("Mean Score:", df['Score'].mean())
2. Filtering, Grouping, Missing Data
Theory:
Data cleaning and grouping are crucial before training AI models. Pandas provides built-in
functions to filter data, handle missing values, and aggregate information.
Code Example:
# Filtering
print("Age > 23:\n", df[df['Age'] > 23])
# Grouping
grouped = [Link]('Age').mean()
print("Grouped by Age:\n", grouped)
# Missing data
[Link][3] = ['Zara', None, 88] # Add row with missing value
print("Missing Data:\n", [Link]())
df['Age'].fillna(df['Age'].mean(), inplace=True) # Fill missing with mean
print("After Filling:\n", df)
3. Merging, Time-Series, Aggregations
Theory:
Merging multiple datasets and working with time-series data are common tasks in AI for real-
world applications such as stock prediction or IoT.
Code Example:
# Merging two DataFrames
df2 = [Link]({'Name': ['Ali', 'Sara'],
'City': ['Lahore', 'Karachi']})
merged = [Link](df, df2, on='Name', how='left')
print("Merged Data:\n", merged)
# Time Series
dates = pd.date_range('2025-01-01', periods=6, freq='D')
ts = [Link]([10, 15, 20, 25, 30, 35], index=dates)
print("Time Series:\n", ts)
print("Rolling Mean:\n", [Link](3).mean())
3 Matplotlib
1. Basic Plotting
Theory:
Matplotlib is a plotting library for Python. In AI, it is used to visualize datasets, training curves,
and predictions.
Code Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y, label="y=2x", color="blue")
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Basic Line Plot")
[Link]()
[Link]()
2. Intermediate Level – Subplots & Bar Charts
Theory:
Multiple plots are useful for comparing different models or dataset features.
Code Example:
import numpy as np
x = [Link](1, 6)
y1 = x ** 2
y2 = x ** 3
# Subplots
[Link](1, 2, 1)
[Link](x, y1, color="green")
[Link]("Square Function")
[Link](1, 2, 2)
[Link](x, y2, color="red")
[Link]("Cubic Function")
plt.tight_layout()
[Link]()
3. Histograms, 3D Plots, Heatmaps
Theory:
Advanced visualizations help analyze high-dimensional data. Histograms show distributions, 3D
plots display relationships, and heatmaps are useful for correlation analysis.
Code Example:
from mpl_toolkits.mplot3d import Axes3D
# Histogram
data = [Link](1000)
[Link](data, bins=30, color='purple')
[Link]("Histogram of Random Data")
[Link]()
# 3D Plot
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
x = [Link](50)
y = [Link](50)
z = [Link](50)
[Link](x, y, z, c='blue', marker='o')
[Link]("3D Scatter Plot")
[Link]()