There are three ways of calculating the square of each element in NumPy array:
np.square()
calculates the square of every element in NumPy array. It does not modify the original NumPy array and returns the element-wise square of the input array.
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) newarr = np.square(arr) print('Original array:') print(arr) print('Squared array:') print(newarr)
Output
Original array: [[1 2 3 4] [5 6 7 8]] Squared array: [[ 1 4 9 16] [25 36 49 64]]
while
loop is used to loop through every element of NumPy array. During each iteration, the square of the element is calculated and stored in the original array.
import numpy as np arr = np.array([1, 2, 3, 4]) i=0 while i < arr.size: arr[i] = arr[i]*arr[i] i = i + 1 print(arr)
Output
[ 1 4 9 16]
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) rows, cols = arr.shape i=0 while i < rows: j = 0 while j < cols: arr[i, j] = arr[i, j]*arr[i, j] j = j + 1 i = i + 1 print(arr)
Output
[[ 1 4 9 16] [25 36 49 64]]
By default, nditer
does not allow the modification of NumPy array. To overcome this problem, you will need to use op_flags
parameter and pass readwrite
value to it.
import numpy as np arr = np.array([1, 2, 3, 4]) for t in np.nditer(arr, op_flags=['readwrite']): t[...] = t*t print(arr)
Output
[ 1 4 9 16]
import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) for t in np.nditer(arr, op_flags=['readwrite']): t[...] = t*t print(arr)
Output
[[ 1 4 9 16] [25 36 49 64]]