I am working on some array T and a condition based on the array D:
import numpy as np
T = np.array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8]])
D = np.array([-6, 1, 5, -8])
What I want to do for each row of T:
if
D<0replace first value by the second value and second value by the opposite of first value, for example[ 1, 2] -> [ 2, -1]asD[0]<0if
D>0replace first value by the opposite of second value and second value by the first value, for example[ 3, 4] -> [-4, 3]asD[1]>0
I did this by using this (ugly) code:
import numpy as np
T = np.array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8]])
D = np.array([-6, 1, 5, -8])
n = len(T)
NrT = T.copy()
for idx in range(n):
if D[idx] > 0:
NrT[idx,0] = -T[idx,1]
NrT[idx,1] = +T[idx,0]
else:
NrT[idx,0] = +T[idx,1]
NrT[idx,1] = -T[idx,0]
NrT
Would it be possible to use some vectorized function lambda to do the same thing more elegantly, in the possible shape:
f = lambda *some expression I was not able to find*
NrT = np.apply_along_axis(f, axis=1, arr=T)
I'm not used to using lambda functions. Is there perhaps an easier way to do it?
def f()instead oflamba. And later you may try to reduce it to lamba. But maybe normal function would be simpler and more readable. And normal function you still can use inapply_along_axisapply_along_axisiterates on the other axis/axes, sending 1d arays to your (lambda) function. With a 2d array likeTyou could just as easily (and as fast) iterate on axis 0, passingT[i]to the function. So it's not a true 'vectorization'. Andapplydoesn't work with 2 arrays.idx1=D>0andidx2=D<=0. And thenNrT[idx1] = ...T[idx1]etc