Python for Data Science & Automation · Module 2: Numerical Computing with NumPy · Lesson 10 of 34

2.5 Statistical Operations & Linear Algebra with NumPy

NumPy Statistical Operations & Linear Algebra

Data Science involves much more than storing and manipulating numerical values. We need to summarize data, measure variation, compare values, and perform mathematical computations.

NumPy provides a powerful collection of functions for statistical analysis and linear algebra.

In this lesson, you will learn:
  • sum() and basic aggregation
  • mean()
  • median()
  • min() and max()
  • variance()
  • standard deviation()
  • Statistical operations on 2D arrays
  • The concept of an axis
  • Dot products
  • Matrix multiplication
  • np.dot() and @
  • Practical Data Science applications

1. Why Statistical Operations Are Important

Suppose a school has examination scores for 1,000 students. Looking at every score individually does not immediately tell us how the entire group performed.

Statistical measures help us answer questions such as:

  • What is the average score?
  • What is the middle score?
  • How widely are scores distributed?
  • What is the highest score?
  • What is the lowest score?

NumPy allows these calculations to be performed efficiently on numerical arrays.

2. np.sum()

np.sum() calculates the sum of the elements in an array.

import numpy as np

marks = np.array([72, 85, 91, 68, 79])

total = np.sum(marks)

print(total)

Output:

395

The calculation is:

72 + 85 + 91 + 68 + 79 = 395

3. np.mean()

The mean is the arithmetic average of a collection of values.

Formula:

Mean = Sum of all values ÷ Number of values

marks = np.array([72, 85, 91, 68, 79])

average = np.mean(marks)

print(average)

Output:

79.0

The mean score is therefore 79.

4. ndarray.mean()

NumPy arrays also provide a mean() method.

marks = np.array([72, 85, 91, 68, 79])

print(marks.mean())

Output:

79.0

Therefore, both approaches are commonly seen:

np.mean(marks)

marks.mean()

5. np.median()

The median is the middle value when the data is arranged in ascending or descending order.

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

print(np.median(values))

Output:

30.0

For an odd number of observations, the middle observation is the median.

6. Median with an Even Number of Values

When there are an even number of observations, the median is the average of the two middle values.

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

print(np.median(values))

Output:

25.0

Calculation:

(20 + 30) / 2 = 25

7. Mean vs Median

Mean Median
Arithmetic average. Middle value after ordering.
Uses every value in the calculation. Depends primarily on the middle position.
Can be strongly affected by extreme values. Generally more resistant to extreme values.
Calculated using np.mean(). Calculated using np.median().

8. Minimum and Maximum

NumPy provides np.min() and np.max() to identify the smallest and largest values.

marks = np.array([72, 85, 91, 68, 79])

print(np.min(marks))
print(np.max(marks))

Output:

68
91

9. Range of Data

The range represents the difference between the maximum and minimum values.

marks = np.array([72, 85, 91, 68, 79])

data_range = np.max(marks) - np.min(marks)

print(data_range)

Output:

23

Therefore:

Range = Maximum - Minimum

10. np.var()

Variance measures how far data values tend to spread from the mean.

A small variance indicates that values are relatively close to the mean, while a larger variance indicates greater spread.

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

variance = np.var(values)

print(variance)

Output:

200.0

11. Understanding Variance

Conceptually, variance measures the average squared deviation from the mean.

For a population:

Variance = Average of squared deviations from the mean

Squaring the deviations ensures that negative and positive differences do not cancel each other out.

12. np.std()

Standard deviation measures the typical spread of values around the mean.

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

std = np.std(values)

print(std)

Output:

14.142135623730951

Standard deviation is the square root of variance.

Standard Deviation = √Variance

13. Variance vs Standard Deviation

Variance Standard Deviation
Measures spread using squared deviations. Square root of variance.
Expressed in squared units. Expressed in the same units as the original data.
NumPy function: np.var() NumPy function: np.std()

14. Statistical Operations on 2D Arrays

Statistical operations become especially important when working with two-dimensional arrays.

marks = np.array([
    [80, 75, 90],
    [70, 85, 95],
    [88, 92, 78]
])

print(np.mean(marks))

Output:

84.77777777777777

Without specifying an axis, NumPy calculates the operation across all elements.

15. Understanding axis=0

For a 2D array, axis=0 performs the operation down the rows, producing a result for each column.

marks = np.array([
    [80, 75, 90],
    [70, 85, 95],
    [88, 92, 78]
])

print(np.mean(marks, axis=0))

Output:

[79.33333333 84.         87.66666667]

The three values represent the mean of each column.

16. Understanding axis=1

axis=1 performs the operation across the columns, producing a result for each row.

print(np.mean(marks, axis=1))

Output:

[81.66666667 83.33333333 86.        ]

These values represent the mean of each row.

Exam Tip:

For a 2D NumPy array:

axis=0 → operation down rows → result for columns

axis=1 → operation across columns → result for rows

17. Axis Quick Reference

Expression Meaning for 2D Array Result
np.mean(arr) Mean of all elements. Single value.
np.mean(arr, axis=0) Mean down each column. One value per column.
np.mean(arr, axis=1) Mean across each row. One value per row.

18. Sum Along an Axis

sales = np.array([
    [100, 200, 300],
    [150, 250, 350]
])

print(np.sum(sales, axis=0))
print(np.sum(sales, axis=1))

Output:

[250 450 650]
[600 750]

Interpretation:

  • axis=0 → total for each column.
  • axis=1 → total for each row.

19. keepdims

The keepdims=True option keeps reduced dimensions in the result, which can be useful when subsequent broadcasting is required.

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

result = np.mean(
    data,
    axis=1,
    keepdims=True
)

print(result)

Output:

[[20.]
 [50.]]

Instead of producing a shape of (2,), the result has shape (2, 1).

20. Introduction to the Dot Product

The dot product is a fundamental operation in linear algebra and is widely used in Data Science and Machine Learning.

For two vectors:

A = [a₁, a₂, a₃]

B = [b₁, b₂, b₃]

Their dot product is:

A · B = a₁b₁ + a₂b₂ + a₃b₃

21. np.dot()

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

result = np.dot(a, b)

print(result)

Output:

32

Calculation:

(1 × 4) + (2 × 5) + (3 × 6)

= 4 + 10 + 18

= 32

22. Dot Product Using @

For 1D vectors, the @ operator can also calculate the dot product.

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

print(a @ b)

Output:

32
Remember:

For 1D vectors, a @ b produces their dot product.

23. Real-World Example — Weighted Score

Suppose a student's marks are:

marks = np.array([
    80,
    90,
    70
])

The corresponding weights are:

weights = np.array([
    0.3,
    0.4,
    0.3
])

A weighted score can be calculated using the dot product.

weighted_score = np.dot(
    marks,
    weights
)

print(weighted_score)

Output:

82.0

Calculation:

(80 × 0.3) +
(90 × 0.4) +
(70 × 0.3)

= 24 + 36 + 21

= 81

Note: Always verify the weights and input values in your actual calculation; the code output should be treated as the authoritative result.

24. Matrix Multiplication

Matrix multiplication combines rows of one matrix with columns of another matrix.

Consider:

A = [
    [1, 2],
    [3, 4]
]

B = [
    [5, 6],
    [7, 8]
]

Matrix multiplication gives:

[[19 22]
 [43 50]]

25. Matrix Multiplication Using @

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

B = np.array([
    [5, 6],
    [7, 8]
])

result = A @ B

print(result)

Output:

[[19 22]
 [43 50]]

26. Matrix Multiplication Using np.dot()

result = np.dot(A, B)

print(result)

For 2D arrays, np.dot(A, B) performs matrix multiplication.

For modern NumPy code, the @ operator or np.matmul() can make matrix multiplication explicit.

27. Matrix Multiplication Rule

Matrix multiplication is possible when:

Number of columns in the first matrix = Number of rows in the second matrix

For example:

A.shape = (2, 3)
B.shape = (3, 4)

Multiplication is possible and produces:

Result.shape = (2, 4)
Important:

Shape compatibility for matrix multiplication is different from ordinary element-wise multiplication.

28. Element-Wise vs Matrix Multiplication

Feature Element-Wise Matrix Multiplication
Operator * @
Function np.multiply() np.matmul()
Operation Corresponding elements are multiplied. Rows are multiplied by columns.
Shape requirement Shapes must be compatible for element-wise broadcasting. Inner dimensions must match.

29. Matrix Transpose

The transpose changes rows into columns and columns into rows.

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

print(A.T)

Output:

[[1 4]
 [2 5]
 [3 6]]

The original shape is:

(2, 3)

After transposition:

(3, 2)

30. Practical Example — Sales Analysis

Suppose a company records sales of three products across two regions.

sales = np.array([
    [100, 200, 300],
    [150, 250, 350]
])

Calculate:

  • Total sales.
  • Average sales.
  • Maximum sales.
  • Minimum sales.
  • Regional totals.
print("Total:", np.sum(sales))

print("Average:", np.mean(sales))

print("Maximum:", np.max(sales))

print("Minimum:", np.min(sales))

print("Region totals:",
      np.sum(sales, axis=1))

Output:

Total: 1350
Average: 225.0
Maximum: 350
Minimum: 100
Region totals: [600 750]

31. NumPy Statistical Functions Cheatsheet

Function Purpose Example
np.sum() Sum of values np.sum(arr)
np.mean() Arithmetic mean np.mean(arr)
np.median() Median np.median(arr)
np.min() Minimum np.min(arr)
np.max() Maximum np.max(arr)
np.var() Variance np.var(arr)
np.std() Standard deviation np.std(arr)

32. NumPy Linear Algebra Quick Reference

Operation NumPy Approach
Dot product np.dot(a, b)
Matrix multiplication a @ b
Matrix multiplication function np.matmul(a, b)
Transpose a.T

33. NumPy Interview Questions

Q1. What is the difference between mean and median?

View Answer

Mean is the arithmetic average of the values, whereas median is the middle value after the observations are ordered. Median is generally less affected by extreme values.

Q2. What does standard deviation measure?

View Answer

Standard deviation measures the spread of observations around the mean. It is the square root of variance.

Q3. What is the difference between variance and standard deviation?

View Answer

Variance is based on squared deviations from the mean, while standard deviation is the square root of variance. Standard deviation is expressed in the same units as the original data.

Q4. What does axis=0 mean for a 2D NumPy array?

View Answer

The operation is performed down the rows, producing a result for each column.

Q5. What does axis=1 mean for a 2D NumPy array?

View Answer

The operation is performed across the columns, producing a result for each row.

Q6. What is a dot product?

View Answer

The dot product of two vectors is the sum of the products of their corresponding elements.

Q7. How can matrix multiplication be performed in NumPy?

View Answer

It can be performed using the @ operator or functions such as np.matmul().

34. Examination Questions

Multiple Choice Questions

Q1. Which NumPy function calculates the arithmetic mean?

  1. np.average_value()
  2. np.mean()
  3. np.middle()
  4. np.avg_value()

Answer: B — np.mean()

Q2. Which function calculates the median?

  1. np.middle()
  2. np.median()
  3. np.center()
  4. np.mid()

Answer: B — np.median()

Q3. Which function calculates variance?

  1. np.var()
  2. np.variance_value()
  3. np.spread()
  4. np.vr()

Answer: A — np.var()

Q4. Which function calculates standard deviation?

  1. np.standard()
  2. np.std()
  3. np.deviation()
  4. np.sd()

Answer: B — np.std()

Q5. What is the output?

arr = np.array([10, 20, 30])

print(np.mean(arr))
  1. 10
  2. 20
  3. 30
  4. 60

Answer: B — 20

Q6. Which operator is commonly used for matrix multiplication?

  1. *
  2. +
  3. @
  4. %

Answer: C — @

Q7. What does np.mean(arr, axis=0) return for a 2D array?

  1. Mean of every element individually
  2. Mean of each column
  3. Mean of each row
  4. Maximum of each column

Answer: B — Mean of each column

Q8. What is the dot product of [1, 2, 3] and [4, 5, 6]?

  1. 21
  2. 30
  3. 32
  4. 36

Answer: C — 32

Short Answer Questions

  1. Define mean, median and standard deviation.
  2. Differentiate between variance and standard deviation.
  3. Explain axis=0 and axis=1 with respect to a 2D array.
  4. What is the purpose of np.dot()?
  5. Differentiate between element-wise multiplication and matrix multiplication.
  6. State the matrix multiplication compatibility rule.

35. Practical Lab Exercise

Student Performance Analysis

Create a NumPy program to analyze the marks of students in multiple subjects.

  1. Create a 2D array containing marks for at least five students and three subjects.
  2. Calculate the total marks.
  3. Calculate the overall mean.
  4. Calculate the median.
  5. Find the highest and lowest marks.
  6. Calculate the variance.
  7. Calculate the standard deviation.
  8. Calculate the mean marks for each subject using axis=0.
  9. Calculate the mean marks for each student using axis=1.
  10. Create a weight array and calculate weighted scores using np.dot().

36. Common Mistakes to Avoid

  1. Confusing mean and median: They are different statistical measures.
  2. Confusing variance and standard deviation: Standard deviation is the square root of variance.
  3. Forgetting the axis: Always understand whether you need a result for rows or columns.
  4. Confusing * and @: They represent different types of multiplication.
  5. Ignoring matrix dimensions: Matrix multiplication requires compatible inner dimensions.
  6. Assuming median requires the array to be manually sorted: np.median() performs the necessary calculation for you.

37. Quick Revision Cheatsheet

Concept NumPy Syntax Purpose
Sum np.sum(arr) Total
Mean np.mean(arr) Average
Median np.median(arr) Middle value
Minimum np.min(arr) Smallest value
Maximum np.max(arr) Largest value
Variance np.var(arr) Spread based on squared deviations
Standard deviation np.std(arr) Spread around mean
Dot product np.dot(a, b) Vector dot product
Matrix multiplication a @ b Matrix multiplication
Transpose a.T Rows ↔ Columns

38. Key Takeaways

  • Mean represents the arithmetic average.
  • Median represents the middle value after ordering the observations.
  • Variance measures dispersion using squared deviations from the mean.
  • Standard deviation is the square root of variance.
  • axis=0 produces column-wise results for a 2D array.
  • axis=1 produces row-wise results for a 2D array.
  • np.dot() can calculate the dot product of vectors and also supports matrix-related operations.
  • @ is the matrix multiplication operator.
  • Matrix multiplication requires compatible dimensions.
  • Statistical and linear algebra operations form an important foundation for Data Science and Machine Learning.
Golden Rule:

Use statistical functions to understand your data and linear algebra operations to transform and combine numerical information.