SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 13
← Back to Course Index

NumPy


On This Page

Module 13: NumPy


13.1  Why NumPy?

NumPy (Numerical Python) is the foundational library for numerical computing in Python. It introduces the array — a data structure that is far faster and more memory-efficient than a regular Python list for numeric operations, and is the backbone that Pandas itself is built on.

FeaturePython ListNumPy Array
SpeedSlower for large dataMuch faster (vectorized operations)
Math operationsRequires loopsDirect: array + 5 adds to every element
Memory usageHigherLower (fixed data type)
Multi-dimensional dataAwkward (nested lists)Native support (2D, 3D+ arrays)
► Installing & Importing NumPy
pip install numpy

import numpy as np

13.2  Creating Arrays

► Creating NumPy Arrays
import numpy as np

marks = np.array([78, 85, 92, 66, 88])
print(marks)
print(type(marks))

matrix = np.array([[1,2,3],[4,5,6]])   # 2D array
print(matrix)

zeros = np.zeros(5)         # array of 5 zeros
ones = np.ones((2,3))       # 2x3 array of ones
seq = np.arange(0, 10, 2)   # like range(), but returns an array
Output
[78 85 92 66 88]
<class 'numpy.ndarray'>
[[1 2 3]
[4 5 6]]

13.3  Indexing

► Indexing NumPy Arrays
marks = np.array([78, 85, 92, 66, 88])
print(marks[0])       # first element
print(marks[-1])      # last element

matrix = np.array([[1,2,3],[4,5,6]])
print(matrix[0, 2])   # row 0, column 2 -> 3
print(matrix[1, :])   # entire second row
Output
78
88
3
[4 5 6]

13.4  Slicing

► Slicing NumPy Arrays
marks = np.array([78, 85, 92, 66, 88, 95])
print(marks[1:4])     # index 1 to 3
print(marks[:3])      # first 3 elements
print(marks[::2])     # every 2nd element
Output
[85 92 66]
[78 85 92]
[78 92 88]

13.5  Broadcasting

Broadcasting lets NumPy apply an operation to every element of an array automatically, without writing a loop — this is one of NumPy's most powerful features.

► Broadcasting Example
marks = np.array([70, 80, 90])
bonus_marks = marks + 5      # adds 5 to EVERY element automatically
print(bonus_marks)

scaled = marks * 1.1          # 10% boost to every element
print(scaled)
Output
[75 85 95]
[77. 88. 99.]
✓ Why This Matters
Without broadcasting, you would need a for loop to add 5 to every mark. NumPy does this instantly across the entire array — this is what makes it dramatically faster for large datasets.

13.6  Mathematical Operations

► Element-wise Math Operations
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])

print(a + b)     # [11 22 33]
print(a - b)     # [9 18 27]
print(a * b)     # [10 40 90]
print(a / b)     # [10. 10. 10.]

13.7  Aggregation Functions

FunctionPurpose
np.sum(arr)Total of all elements
np.mean(arr)Average value
np.max(arr) / np.min(arr)Largest / smallest value
np.std(arr)Standard deviation
np.median(arr)Median value
► Aggregation in Action
marks = np.array([78, 85, 92, 66, 88])
print("Mean:", np.mean(marks))
print("Max:", np.max(marks))
print("Std Dev:", round(np.std(marks), 2))
Output
Mean: 81.8
Max: 92
Std Dev: 9.19

13.8  Reshaping Arrays

reshape() lets you change an array's dimensions without changing its data — very useful when preparing data for analysis or ML models.

► Reshaping Example
data = np.arange(1, 13)         # 1D array: 1 to 12
reshaped = data.reshape(3, 4)   # 3 rows, 4 columns
print(reshaped)
Output
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
✗ Common Mistake
reshape() will raise an error if the total number of elements doesn't match the new shape (e.g. reshaping 10 elements into a 3x4 grid, which needs 12). Always check that rows × columns = total elements.

13.9  Practical Exercises

Basic (5 Questions)

1. Create a NumPy array of 6 exam marks and print its type.

2. Create a 2x3 array of zeros and a 3x2 array of ones.

3. Print the first and last element of an array using indexing.

4. Slice an array to get only the middle 3 elements.

5. Use np.arange() to create an array of even numbers from 0 to 20.

Intermediate (5 Questions)

1. Use broadcasting to add 10 bonus marks to an array of student scores.

2. Calculate the mean, max, min, and standard deviation of a marks array.

3. Create a 2D array (3x3) and access a specific row and a specific element.

4. Reshape a 1D array of 9 elements into a 3x3 grid.

5. Multiply two arrays element-wise and print the result.

Advanced (5 Questions)

1. Build a 'Grade Booster' that adds different bonus points to different subjects using broadcasting on a 2D array.

2. Given a 2D array of student marks (rows = students, columns = subjects), calculate each student's average using aggregation along an axis.

3. Reshape a dataset of 24 sales figures into a 4x6 grid representing 4 weeks x 6 days, then find the weekly totals.

4. Compare the execution speed of summing 1 million numbers using a Python loop vs. np.sum() (using the time module).

5. Build a simple 'Data Normalizer' that scales an array of marks to a 0-1 range using broadcasting: (x - min) / (max - min).

13.10  Module Quiz (MCQs)

Q1. What is the main advantage of NumPy arrays over lists?

Q2. Which function creates an array of evenly spaced values like range()?

Q3. What does broadcasting allow?

Q4. Which function reshapes an array?

Q5. Which function calculates the average of an array?

ℹ Answer Key
1-b, 2-b, 3-b, 4-b, 5-c

13.11  Module Assignment

Assignment: Student Marks Analyzer with NumPy

Expected Output: A script that computes per-student and per-subject averages from a 2D marks array, correctly applying grace marks using broadcasting.

13.12  Interview Questions — Module 13


13.13  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.