How to perform arithmetic operations in NumPy

An interesting feature of NumPy arrays is that we can perform the same mathematical operation on every element with a single command.

Note: Both exponential and logarithmic operations are supported.

import numpy as np
arr = np.array([[5, 10], [15, 20]])
# Add 10 to element values
print("Adding 10: " + repr(arr + 10))
# Multiple elements by 5
print("Multiplying by 5: " + repr(arr * 5))
# Subtract 5 from elements
print("Subtracting 5: " + repr(arr - 5))
# Matrix multiplication
arr1 = np.array([[-8, 7], [17, 20], [8, -16], [11, 4]])
arr2 = np.array([[5, -5, 10, 20], [-8, 0, 13, 2]])
print("Multiplying two arrays: " + repr(np.matmul(arr1, arr2)))
# Exponential
arr3 = np.array([[1, 5], [2.5, 2]])
# Exponential of each element
print("Taking the exponential: " + repr(np.exp(arr3)))
# Cubing all elements
print("Making each element a power of 3: " + repr(np.power(3, arr3)))

Statistics & aggregation

Since the goal is to produce something useful out of a dataset, NumPy offers several statistical tools such as min, max, median, mean and sum.

import numpy as np
arr = np.array([[18, 5, -25],
[-10, 30, 7],
[8, 16, -2]])
print "Min: ", arr.min()
print "Max: ", arr.max()
print "Sum: ", np.sum(arr)
print "Mean: ", np.mean(arr)
print "Median: ", np.median(arr)
print "Variance: ", np.var(arr)
svg viewer

Data saving

In NumPy, all our data can be saved using the save method. This will create a file with the .npy extension containing all our data.

The load method can load the data from a .npy file back into the program.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved