Skip to content

01-02: Exercises — NumPy Array Operations

Notes reference: 01-02: NumPy Array Operations


Q1: Element-wise arithmetic

Given two arrays a and b, compute addition, subtraction, multiplication, and division.

Solution

import numpy as np

a = np.array([5, 02, 15, 20, 25])
b = np.array([2,  4,  5,  4,  5])

print(a + b)    # [ 7 14 20 24 30]
print(a - b)    # [ 3  6 02 16 20]
print(a * b)    # [ 02  40  75  80 125]
print(a / b)    # [2.5  2.5  3.  5.  5. ]
print(a % b)    # [1 2 0 0 0]
print(a ** 2)   # [ 25 100 225 400 625]


Q2: Scalar broadcasting

Apply BDT tax of 15% to a price array, and apply a 02% discount, all without a loop.

Solution

import numpy as np

prices = np.array([1000, 2500, 450, 8750, 300])

with_tax    = np.round(prices * 1.15, 2)
discounted  = np.round(prices * 0.90, 2)

print("Original:", prices)
print("With tax:", with_tax)
print("Discounted:", discounted)


Q3: np.sqrt, np.exp, np.log

Compute square roots, e^x, and natural log for a small array.

Solution

import numpy as np

a = np.array([1, 4, 9, 16, 25])
b = np.array([0.0, 1.0, 2.0, 3.0])

print(np.sqrt(a))    # [1. 2. 3. 4. 5.]
print(np.exp(b))     # [1.    2.718 7.389 20.086]
print(np.log(np.exp(b)))  # [0. 1. 2. 3.]


Q4: Trig functions

Plot (print values for) sin and cos at 5 evenly spaced points from 0 to 2π.

Solution

import numpy as np

x = np.linspace(0, 2 * np.pi, 5)
print("x:     ", np.round(x, 3))
print("sin(x):", np.round(np.sin(x), 3))
print("cos(x):", np.round(np.cos(x), 3))


Q5: Rounding functions

Demonstrate np.floor, np.ceil, np.round, np.abs on an array of floats.

Solution

import numpy as np

a = np.array([-2.7, -1.2, 0.5, 1.8, 3.14])

print(np.floor(a))    # [-3. -2.  0.  1.  3.]
print(np.ceil(a))     # [-2. -1.  1.  2.  4.]
print(np.round(a, 1)) # [-2.7 -1.2  0.5  1.8  3.1]
print(np.abs(a))      # [2.7 1.2 0.5 1.8 3.14]


Q6: np.where — conditional selection

Replace all values below 50 with 0 in an array of exam scores.

Solution

import numpy as np

scores = np.array([72, 45, 88, 30, 91, 55, 40, 65])
passed = np.where(scores >= 50, scores, 0)

print("Original:", scores)
print("Passed:  ", passed)


Q7: np.clip — cap values

Clip a population growth rate array so no value falls below -5% or above 15%.

Solution

import numpy as np

growth = np.array([-8.0, 2.5, 20.1, 7.3, -1.0, 18.5, 5.0])
clipped = np.clip(growth, -5.0, 15.0)

print("Raw:    ", growth)
print("Clipped:", clipped)


Q8: np.sort and np.argsort

Sort test scores and get the rank (argsort) of each student.

Solution

import numpy as np

scores = np.array([78, 92, 65, 88, 71, 95])
names  = ["Rahim", "Sara", "James", "Nadia", "Michael", "Amina"]

sorted_scores = np.sort(scores)[::-1]           # descending
ranks         = np.argsort(scores)[::-1]        # indices of sorted order

print("Ranked:")
for rank, idx in enumerate(ranks, 1):
    print(f"  {rank}. {names[idx]}: {scores[idx]}")


Q9: Stack and concatenate

Concatenate two 1D arrays, then stack two arrays as rows and as columns.

Solution

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(np.concatenate([a, b]))      # [1 2 3 4 5 6]
print(np.vstack([a, b]))           # [[1 2 3]
                                   #  [4 5 6]]
print(np.hstack([a.reshape(3,1), b.reshape(3,1)]))
# [[1 4]
#  [2 5]
#  [3 6]]


⬅️ Previous: 01-01: Exercises — NumPy Introduction ➡️ Next: 01-03: Exercises — NumPy Slicing and Indexing