I have the following numpy array :
A = np.array([[1,2,3,4,5],
[15,25,35,45,55]])
I would like to create a new array with the same shape by dividing each dimension by the last element of the dimension
The output desired would be :
B = np.array([[0.2,0.4,0.6,0.8,1],
[0.27272727,0.45454545,0.63636364,0.81818182,1]])
Any idea ?
CodePudding user response:
Slice the last element while keeping the dimensions and divide:
B = A/A[:,[-1]] # slice with [] to keep the dimensions
or, better, to avoid an unnecessary copy:
B = A/A[:,-1,None]
output:
array([[0.2 , 0.4 , 0.6 , 0.8 , 1. ],
[0.27272727, 0.45454545, 0.63636364, 0.81818182, 1. ]])
CodePudding user response:
You mean this?
B = np.array([[A[i][j]/A[i][len(A[i])-1] for j in range(0,len(A[i]))] for i in range(0,len(A))])
CodePudding user response:
You can achieve this using:
[list(map(lambda i: i / a[-1], a)) for a in A]
Result:
[[0.2, 0.4, 0.6, 0.8, 1.0], [0.2727272727272727, 0.45454545454545453, 0.6363636363636364, 0.8181818181818182, 1.0]]
CodePudding user response:
Adding on @mozway answer, it seems to be faster to take the last column and then add an axis with:
B = A/A[:,-1][:,None]
for instance.