The reshape()
function in NumPy is a powerful tool which allows us to restructure an array according to the arguments we specify.
The function takes in an array and a new shape as required arguments. The new shape must exactly contain all the elements from the input array. For example, we could reshape an array with 8
elements to (4, 2)
, but not (4, 3)
.
-1
is a special argument which can only be used once as a dimension. The -1
dimension will take on the value necessary to allow the new shape to contain all the elements of the array.
NumPy also has a variety of other shaping functions, such as flatten
or transpose
.
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)))
Free Resources