Mastering NumPy in Python: The Backbone of Scientific Computing

5.72K 0 0 0 0

Chapter 3: Mathematical and Statistical Operations in NumPy

🔹 1. Introduction

One of the most powerful features of NumPy is its ability to perform fast, vectorized mathematical and statistical operations on arrays. Whether you're doing basic arithmetic, aggregating data, or applying statistical analysis across large datasets, NumPy makes it both efficient and intuitive.

In this chapter, we’ll explore:

  • Element-wise arithmetic
  • Aggregation functions
  • Universal functions (ufuncs)
  • Broadcasting rules
  • Real-world examples

These features form the backbone of data science, engineering simulations, image processing, and machine learning workflows.


🔹 2. Element-wise Arithmetic Operations

NumPy supports all standard arithmetic operations between arrays or between arrays and scalars.

Example:

import numpy as np

 

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

b = np.array([4, 5, 6])

 

print(a + b)   # [5 7 9]

print(a - b)   # [-3 -3 -3]

print(a * b)   # [4 10 18]

print(a / b)   # [0.25 0.4  0.5 ]

print(a ** 2)  # [1 4 9]

These are vectorized operations — no need for loops!


🔹 3. Aggregate (Reduction) Functions

Aggregate functions operate over an entire array (or along an axis).

Common Functions:

Function

Description

np.sum()

Sum of elements

np.mean()

Arithmetic mean

np.median()

Median value

np.std()

Standard deviation

np.var()

Variance

np.min()

Minimum value

np.max()

Maximum value

Example:

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

 

print(np.sum(arr))        # 21

print(np.mean(arr))       # 3.5

print(np.std(arr))        # 1.7078

print(np.sum(arr, axis=0))  # Column-wise sum: [5 7 9]

print(np.sum(arr, axis=1))  # Row-wise sum: [6 15]


🔹 4. Universal Functions (ufuncs)

Universal functions (ufuncs) are NumPy's way of applying element-wise operations.

Examples:

x = np.array([1, 4, 9, 16])

 

np.sqrt(x)      # Square root

np.log(x)       # Natural logarithm

np.exp(x)       # Exponential

np.sin(x)       # Sine

np.cos(x)       # Cosine

np.abs(x)       # Absolute value

Ufuncs are much faster than looping over arrays.


🔹 5. Mathematical Constants

NumPy also provides mathematical constants:

np.pi       # 3.141592...

np.e        # 2.718281...

np.inf      # Infinity

np.nan      # Not a Number


🔹 6. Rounding and Precision

You can control the precision of floating-point results using rounding functions.

a = np.array([3.14159, 2.71828])

 

np.round(a, 2)    # [3.14 2.72]

np.floor(a)       # [3. 2.]

np.ceil(a)        # [4. 3.]

np.trunc(a)       # [3. 2.]


🔹 7. Broadcasting in Arithmetic

Broadcasting lets you operate on arrays of different shapes.

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

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

 

print(a + b)

# [[11 22 33]

#  [14 25 36]]

Broadcasting Rules:

  • Dimensions are compared from right to left.
  • Dimensions must either be equal or one of them is 1.

🔹 8. Applying Mathematical Functions on Axes

You can apply operations across rows or columns using the axis parameter.

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

 

np.mean(arr, axis=0)  # Column-wise mean: [2.5 3.5 4.5]

np.mean(arr, axis=1)  # Row-wise mean: [2.0 5.0]


🔹 9. Cumulative and Difference Functions

NumPy supports accumulation and difference calculations:

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

 

np.cumsum(arr)    # [1 3 6 10]

np.cumprod(arr)   # [1 2 6 24]

np.diff(arr)      # [1 1 1]


🔹 10. Real-World Example: Grades Analysis

grades = np.array([[87, 90, 85],

                   [70, 88, 92],

                   [95, 100, 98]])

 

student_avg = np.mean(grades, axis=1)

subject_avg = np.mean(grades, axis=0)

 

print("Student Averages:", student_avg)

print("Subject Averages:", subject_avg)

Output:

Student Averages: [87.33 83.33 97.67]

Subject Averages: [84.   92.67 91.67]


🔹 11. Summary Table

Operation

Function/Example

Description

Sum

np.sum(arr)

Total sum of array elements

Mean

np.mean(arr)

Average of values

Std Dev

np.std(arr)

Spread of data

Element-wise

arr ** 2, arr + 10

Fast array math

Broadcasting

arr + scalar or arr + arr2

Auto-expanding shape

Ufuncs

np.exp(arr), np.log(arr)

Element-wise math functions



Back

FAQs


1. What is NumPy used for?

NumPy is used for numerical computations, array operations, linear algebra, and data processing in Python.

2. How is NumPy different from regular Python lists?

NumPy arrays are faster, use less memory, and support vectorized operations, unlike Python lists which are slower and less flexible for numerical tasks

3. What is an ndarray in NumPy?

It’s the core data structure in NumPy — an N-dimensional array that allows element-wise operations and advanced indexing.

4. Is NumPy part of the standard Python library?

No, it needs to be installed separately using pip install numpy.

5. What are broadcasting rules in NumPy?

Broadcasting allows NumPy to perform operations on arrays of different shapes by automatically expanding them to be compatible.

6. Can NumPy be used for linear algebra and matrix operations?

Yes, it provides comprehensive support for matrix multiplication, eigenvalues, singular value decomposition, and more.

7. Is NumPy suitable for big data or deep learning?

While NumPy is essential for preprocessing and fast array computations, deep learning libraries like TensorFlow or PyTorch build on top of it for more advanced tasks.

8. Can I use NumPy with Pandas and Matplotlib?

Absolutely Pandas is built on NumPy arrays, and Matplotlib supports NumPy for plotting.

9. Does NumPy support random number generation?

Yes the numpy.random module offers distributions like normal, binomial, uniform, etc.

10. Is NumPy faster than Python loops?

Significantly. NumPys vectorized operations are typically 10x to 100x faster than traditional for-loops in Python.