If we have a 2D array. Suppose I would like to square the first item of a row and store it and then take the cube of the second item and store it as again in the original array. One way is to iterate over array:
#arr shape is (2,2)
arr = np.array([[1, 2], [4, 5]], np.int32)
squarred = np.zeros((arr.shape[0], 2))
squarred [:,0] = arr[:,0]*arr[:,0]
squarred [:,1] = arr[:,1] * arr[:,1] * arr[:,1]
Question: Can we do the same thing using loop iteration please? This is a sample for 2D array. What if we have arbitrary array of any size and we would like to change each element in every row to a custom value, what would be you most efficient approach please?
Edit:
- 2D array of size (2,2) and same for output. But the output element have the first element of each row squared and the second cubed. In general, what would be the most efficient way to do it given we have even larger arrays please?
- Can you please post your answer for a element-wise change of each value in each row to arbitrary value please?
CodePudding user response:
Use numpy.power
function:
# 1xN could also be [3, 5], [2, 8], or any array of size N
exponents_per_row = np.arange(2, 4)
exponents = np.tile(exponents_per_row, (2, 1))
res = np.power(arr, exponents)
print(res)
Output
[[ 1 8]
[ 16 125]]