Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
arithmetic

How to perform arithmetic operations in NumPy

Educative Answers Team

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)