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 nparr = np.array([[5, 10], [15, 20]])# Add 10 to element valuesprint("Adding 10: " + repr(arr + 10))# Multiple elements by 5print("Multiplying by 5: " + repr(arr * 5))# Subtract 5 from elementsprint("Subtracting 5: " + repr(arr - 5))# Matrix multiplicationarr1 = 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)))# Exponentialarr3 = np.array([[1, 5], [2.5, 2]])# Exponential of each elementprint("Taking the exponential: " + repr(np.exp(arr3)))# Cubing all elementsprint("Making each element a power of 3: " + repr(np.power(3, arr3)))
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 nparr = 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)