Sitemap
Aamer Paul

Aamer Paul

Software Engineer | 8+ yrs experience | Java, Kotlin, Python, JS/TS, Spring Boot, Microservices & Mobile Dev | Exploring Backend, ML, Generative AI & LLMs

Numpy Operations

6 min readFeb 17, 2024

--

Press enter or click to view image in full size
Photo by dominik hofbauer on Unsplash

In this post, we will delve into NumPy operations, exploring the core functionalities and demonstrating how to perform various mathematical and array manipulation in NumPy. From basic arithmetic operations to advanced linear algebra functions, NumPy offers a comprehensive set of tools to tackle complex computational challenges effectively.

Before diving in, be sure to check out my previous post.

NumPy includes a wide range of mathematical functions and operations. Some of the key mathematical operations provided by NumPy are:

Basic arithmetic operations:

NumPy’s arithmetic operators on arrays perform elementwise operations, meaning each element in the input arrays is operated upon individually. A new array is created and filled with the results of the arithmetic operation. Some of the arithmetic functions in NumPy include:

  1. Addition: np.add(a, b) or a + b
  2. Subtraction: np.subtract(a, b) or a - b
  3. Multiplication: np.multiply(a, b) or a * b
  4. Division: np.divide(a, b) or a / b
  5. Floor division: np.floor_divide(a, b) or a // b
  6. Exponentiation: np.power(a, b) or a ** b
  7. Modulus: np.mod(a, b) or a % b

Example:

import numpy as np

arr1 = np.array([2, 4, 6, 8])
print(arr1 + 2) # [ 4 6 8 10]

In above example, 2 is added to each element in the array arr1. A new array is created and filled with the result of the operation. We can also use NumPy's add function instead of + operator. Same applies to other mathematical operations.

np.subtract(arr1, 2) # [0 2 4 6]
np.multiply(arr1, 2) # [ 4 8 12 16]
arr1 / 2 # [1. 2. 3. 4.]
arr1 // 2 # [1 2 3 4]
arr1 % 2 # [0 0 0 0]
arr1 **= 2 # modifies existing array rather than create a new one.
print(arr1) # [ 4 16 36 64]

We can also perform operations on multiple arrays.

arr1 = np.array([2, 4, 6, 8])
arr2 = np.arange(1, 5)

arr1 + arr2 # [ 3 6 9 12]
np.floor_divide(arr1, arr2) # [2 2 2 2]
arr3 = arr1 * arr2
arr1 * arr2 * arr3 # [ 4 64 324 1024]

When operating with arrays of different types, the resultant array type corresponds to the more general or precise one (a behavior known as upcasting).

arr1 = np.array([2, 4, 6, 8]) # array of type int
arr2 = np.arange(1, 5, dtype=float) # array of type float
arr1 + arr2 # [ 3. 6. 9. 12.] # upcasted to float

Broadcasting

In the above examples, you may have noticed that we were able to perform arithmetic operations between scalars and arrays seamlessly. This capability is made possible by broadcasting.

Broadcasting allows arithmetic operations to be performed on arrays of different shapes. The broadcasting rule in NumPy states that arrays with smaller dimensions are padded with ones on their leading (left) side to match the shape of the arrays with larger dimensions. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.

a = np.array([1, 2, 3], dtype=int)
# define a scalar
b = 2
# multiply by array by a scalar
print(a * b) #[2 4 6]
Broadcasting Example

The above example is similar to:

a = np.array([1, 2, 3], dtype=int)
b = np.array([2, 2, 2], dtype=int)
print(a * b)

Trigonometric functions:

Trigonometric functions operate elementwise on arrays, applying the trigonometric operation to each element in the array. NumPy provides various trigonometric functions commonly used in mathematics and scientific computing. Some of the key trigonometric functions in NumPy include:

  1. Sine: np.sin(x)
  2. Cosine: np.cos(x)
  3. Tangent: np.tan(x)
  4. Inverse sine: np.arcsin(x)
  5. Inverse cosine: np.arccos(x)
  6. Inverse tangent: np.arctan(x)

These functions accepts array as input and return a new array containing the computed trigonometric values for each element. The input array can be one-dimensional or multidimensional.

Get Aamer Paul’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

np.sin(90) # 0.8939966636005579
arr1 = np.array([45, 90, 180, 360])
np.sin(arr1) # [ 0.85090352 0.89399666 -0.80115264 0.95891572]
np.arctan(arr1) # [1.54857776 1.55968567 1.56524083 1.56801856]

Hyperbolic functions:

Hyperbolic functions in NumPy are mathematical functions that operate elementwise on arrays, applying the hyperbolic operation to each element in the array.

  1. Hyperbolic sine: np.sinh(x)
  2. Hyperbolic cosine: np.cosh(x)
  3. Hyperbolic tangent: np.tanh(x)

Example:

arr1 = np.array([45, 90, 180, 360])
np.cosh(arr1) # [1.74671355e+019 6.10201647e+038 7.44692100e+077 1.10913265e+156]

Exponential and logarithmic functions

Exponential and logarithmic functions are mathematical functions that operate on input values to compute exponential and logarithmic transformations, respectively. In NumPy, these functions operate elementwise on arrays.

  1. Exponential: np.exp(x)
  2. Natural logarithm: np.log(x)
  3. Logarithm base 10: np.log10(x)
  4. Logarithm base 2: np.log2(x)

Example:

np.exp(arr1) # [3.49342711e+019 1.22040329e+039 1.48938420e+078 2.21826530e+156]
np.log10(arr1) # [1.65321251 1.95424251 2.25527251 2.5563025 ]

Linear algebra

NumPy offers a comprehensive set of functions for Linear Algebra computations. Some of the key linear algebra operations provided by NumPy are:

  1. Matrix multiplication: np.dot(a, b) or a @ b
  2. Vector dot product: np.dot(a, b) - Computes the dot product of two vectors.
  3. Determinant: np.linalg.det(a)
  4. Inverse: np.linalg.inv(a) - Computes the inverse of a square matrix.
  5. Transpose: np.transpose(a) or a.T
  6. Trace: np.trace(a) - Computes the sum of the diagonal elements of a matrix.
  7. Eigenvalues and eigenvectors: np.linalg.eig(a) - Computes the eigenvalues and eigenvectors of a square matrix.

These are few examples of Linear Algebra operations provided in NumPy. These operations accept NumPy arrays as input and return NumPy arrays or scalars as output. These functions perform operations on matrices and vectors according to the rules of Linear Algebra.

Example:

arr1 = np.ones((4, 2), dtype=int)
arr2 = np.full((2, 4), 2, dtype=int)

# results in 4x4 matrix
np.dot(arr1, arr2)
# [[4 4 4 4]
# [4 4 4 4]
# [4 4 4 4]
# [4 4 4 4]]

arr1 = np.arange(1, 10, dtype=int).reshape((3,3))
arr2 = np.arange(10, 19, dtype=int).reshape((3,3))
arr2.T
# [[10 13 16]
# [11 14 17]
# [12 15 18]]
np.trace(arr1)
# 15

arr3 = np.identity(3)
np.linalg.det(arr3) # 1.0

Statistical Operations

Statistical operations in NumPy provide functions for computing various descriptive statistics from arrays, such as mean, median, standard deviation, variance, minimum, maximum, and more. These operations operate either on the entire array or along a specified axis. Here are some key statistical operations in NumPy:

  1. Sum: np.sum(a)
  2. Mean: np.mean(a)
  3. Median: np.median(a, axis=None)
  4. Minimum: np.min(a)
  5. Maximum: np.max(a)
  6. Standard deviation: np.std(a)
  7. Variance: np.var(a)
  8. Cumulative sum: np.cumsum(a, axis=None)

These operations accept NumPy arrays as input and return scalar values or arrays containing the computed statistics.

Example:

arr1 = np.arange(1, 10, dtype=int).reshape((3,3))
# arr1:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]

np.sum(arr1) # 45
np.sum(arr1, axis=1) # [12 15 18] - sum of columns
np.median(arr1) # 5.0
np.max(arr1) # 9

np.min(arr1, axis=1) # [1 4 7]

Universal Functions

In NumPy, universal functions (ufuncs) are used for performing efficient, element-wise operations on arrays. We have already discussed some of these in above sections. ufuncs are essentially just mathematical operations that can be used to perform the operation across the array. Some common ones are: np.sin(), np.sqrt(), np.exp(), np.log(), np.max().

Array manipulation

NumPy offers various Array manipulation functions and operations that allow to modify the shape, structure, and content of arrays. These operations enable us to reshape, concatenate, split, stack, and transpose arrays, among other tasks. Here are some key array manipulation functions in NumPy:

  1. Transpose: a.T
  2. Reshape: a.reshape(new_shape)
  3. Flattening Arrays: a.flatten() - Flattens the array 'a' into a 1-D array
  4. Concatenation: np.concatenate((a, b), axis=0) for arrays a and b
  5. Copying Arrays: np.copy(a)
  6. Splitting Arrays: np.split(a, indices_or_sections, axis=0) - Splits an array into multiple sub-arrays along the specified axis

These are few examples of Array manipulation functions provided in NumPy.

Example:

arr1 = np.arange(1, 10, dtype=int).reshape((3,3))
arr2 = np.arange(10, 19, dtype=int).reshape((3,3))
arr1.flatten() # [1 2 3 4 5 6 7 8 9]
arr1.reshape((9, 1))
arr1.T

In next blog, we will discuss Array Manipulation in details.

--

Aamer Paul
Aamer Paul

Written by Aamer Paul

Software Engineer | 8+ yrs experience | Java, Kotlin, Python, JS/TS, Spring Boot, Microservices & Mobile Dev | Exploring Backend, ML, Generative AI & LLMs