1

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<0 replace first value by the second value and second value by the opposite of first value, for example [ 1, 2] -> [ 2, -1] as D[0]<0

  • if D>0 replace first value by the opposite of second value and second value by the first value, for example [ 3, 4] -> [-4, 3] as D[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?

3
  • maybe create normal function def f() instead of lamba. 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 in apply_along_axis Commented Nov 4 at 18:57
  • apply_along_axis iterates on the other axis/axes, sending 1d arays to your (lambda) function. With a 2d array like T you could just as easily (and as fast) iterate on axis 0, passing T[i] to the function. So it's not a true 'vectorization'. And apply doesn't work with 2 arrays. Commented Nov 4 at 19:09
  • Think about using idx1=D>0 and idx2=D<=0. And then NrT[idx1] = ...T[idx1] etc Commented Nov 4 at 19:16

1 Answer 1

3

imho, the easiest way is to prepare an array to multiply original one with, based on your reshaped D array. And then mutiply it with your flipped original T array.

m = np.where(D[:, None]>0, [-1, 1], [1, -1])
res = np.flip(T,1)*m

res:

[[ 2 -1]
 [-4  3]
 [-6  5]
 [ 8 -7]]

P.S. a side-note: I believe using capital letters in array names is not a good idea, especially T - this letter used for transpose method and may make your code look confusing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.