#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read min read

Array Operations

Learn mathematical and element-wise operations on NumPy arrays

Array Operations

Element-wise Arithmetic

Operations happen on each element individually.

Addition

code.py
import numpy as np

arr = np.array([10, 20, 30])
result = arr + 5
print(result)

Output: [15 25 35]

Adding arrays:

code.py
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2
print(result)

Output: [5 7 9]

Subtraction, Multiplication, Division

code.py
import numpy as np

prices = np.array([100, 200, 300])

discounted = prices - 20
print("After discount:", discounted)

doubled = prices * 2
print("Doubled:", doubled)

halved = prices / 2
print("Halved:", halved)

Output:

After discount: [80 180 280] Doubled: [200 400 600] Halved: [50. 100. 150.]

Power and Square Root

code.py
import numpy as np

numbers = np.array([2, 3, 4])
squared = numbers ** 2
print("Squared:", squared)

cubed = numbers ** 3
print("Cubed:", cubed)

roots = np.sqrt(np.array([4, 9, 16]))
print("Square roots:", roots)

Output:

Squared: [4 9 16] Cubed: [8 27 64] Square roots: [2. 3. 4.]

Universal Functions (ufuncs)

Fast operations on arrays.

Trigonometric

code.py
import numpy as np

angles = np.array([0, 30, 45, 60, 90])
radians = np.deg2rad(angles)

sines = np.sin(radians)
cosines = np.cos(radians)

print("Angles:", angles)
print("Sines:", np.round(sines, 2))
print("Cosines:", np.round(cosines, 2))

Exponential and Logarithm

code.py
import numpy as np

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

exp_values = np.exp(numbers)
print("e^x:", exp_values)

log_values = np.log(numbers)
print("ln(x):", log_values)

log10_values = np.log10(np.array([10, 100, 1000]))
print("log10:", log10_values)

Rounding

code.py
import numpy as np

numbers = np.array([1.23, 4.56, 7.89])

print("Round:", np.round(numbers))
print("Floor:", np.floor(numbers))
print("Ceiling:", np.ceil(numbers))

Output:

Round: [1. 5. 8.] Floor: [1. 4. 7.] Ceiling: [2. 5. 8.]

What each does:

  • round: Nearest integer
  • floor: Round down
  • ceil: Round up

Absolute Values

code.py
import numpy as np

numbers = np.array([-5, -3, 0, 2, 4])
absolute = np.abs(numbers)
print(absolute)

Output: [5 3 0 2 4]

Aggregation Functions

Sum, Mean, Median

code.py
import numpy as np

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

print("Sum:", np.sum(data))
print("Mean:", np.mean(data))
print("Median:", np.median(data))

Output:

Sum: 150 Mean: 30.0 Median: 30.0

Min, Max, Range

code.py
import numpy as np

temps = np.array([72, 68, 75, 70, 73])

print("Min:", np.min(temps))
print("Max:", np.max(temps))
print("Range:", np.ptp(temps))

What ptp means: Peak to peak (max - min).

Cumulative Operations

code.py
import numpy as np

sales = np.array([100, 150, 200, 180, 220])

cumsum = np.cumsum(sales)
print("Cumulative sum:", cumsum)

cumprod = np.cumprod(np.array([2, 3, 4]))
print("Cumulative product:", cumprod)

Output:

Cumulative sum: [100 250 450 630 850] Cumulative product: [2 6 24]

Use case: Track running totals over time.

Dot Product

Multiply and sum elements.

code.py
import numpy as np

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

dot = np.dot(a, b)
print("Dot product:", dot)

Output: 32

Calculation: (1×4) + (2×5) + (3×6) = 4 + 10 + 18 = 32

Comparison Operations

code.py
import numpy as np

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

print("Equal:", arr1 == arr2)
print("Greater:", arr1 > arr2)
print("Less or equal:", arr1 <= arr2)

Output:

Equal: [False True False False] Greater: [False False True True] Less or equal: [True True False False]

Logical Operations

code.py
import numpy as np

arr1 = np.array([True, True, False, False])
arr2 = np.array([True, False, True, False])

print("AND:", np.logical_and(arr1, arr2))
print("OR:", np.logical_or(arr1, arr2))
print("NOT:", np.logical_not(arr1))

Clipping Values

Limit values to a range.

code.py
import numpy as np

scores = np.array([45, 78, 105, 92, -5])
clipped = np.clip(scores, 0, 100)
print("Clipped (0-100):", clipped)

Output: [45 78 100 92 0]

What clip does: Values below 0 become 0, above 100 become 100.

Practice Example

The scenario: Calculate monthly budget statistics.

code.py
import numpy as np

income = np.array([3000, 3200, 3100, 3300, 3400])
expenses = np.array([2200, 2400, 2300, 2500, 2600])

savings = income - expenses
print("Monthly savings:", savings)

total_saved = np.sum(savings)
print("Total saved:", total_saved)

average_savings = np.mean(savings)
print("Average savings:", average_savings)

savings_rate = (savings / income) * 100
print("Savings rate (percent):", np.round(savings_rate, 1))

cumulative = np.cumsum(savings)
print("Cumulative savings:", cumulative)

target = 5000
months_to_target = np.where(cumulative >= target)[0]
if len(months_to_target) > 0:
    print("Reached target in month:", months_to_target[0] + 1)

expenses_increase = np.diff(expenses)
print("Month-to-month expense changes:", expenses_increase)

max_savings_month = np.argmax(savings) + 1
print("Best savings month:", max_savings_month)
print("Amount:", savings[max_savings_month - 1])

What this calculates:

  1. Monthly savings (income - expenses)
  2. Total and average savings
  3. Savings rate as percentage
  4. Running total of savings
  5. When target is reached
  6. How expenses changed
  7. Best month for savings

Element-wise vs Matrix Operations

code.py
import numpy as np

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

print("Element-wise multiplication:")
print(a * b)

print("Matrix multiplication:")
print(np.matmul(a, b))

Output:

Element-wise: [[5 12] [21 32]] Matrix: [[19 22] [43 50]]

Key Points to Remember

All basic math operations (+, -, *, /, **) work element-wise on arrays.

NumPy has built-in functions for common operations: sqrt, abs, round, exp, log.

Aggregation functions work on entire array: sum, mean, median, min, max.

Cumulative functions create running totals: cumsum, cumprod.

Comparison operations return boolean arrays that can be used for filtering.

Common Mistakes

Mistake 1: Wrong division operator

code.py
arr / 2  # Float division
arr // 2  # Integer division

Mistake 2: Dimension mismatch

code.py
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2])
arr1 + arr2  # Error! Different sizes

Mistake 3: Modifying during iteration

code.py
for i in range(len(arr)):
    arr[i] = arr[i] * 2  # Slow!

arr = arr * 2  # Fast NumPy way

Mistake 4: Using Python functions

code.py
import math
math.sqrt(arr)  # Error! Use np.sqrt()

What's Next?

You now know array operations. Next, you'll learn about broadcasting - NumPy's way of handling operations on arrays of different shapes.

SkillsetMaster - AI, Web Development & Data Analytics Courses