2

I have a very large array, but I'll use a smaller one to explain.

Given source array X

X = [ [1,1,1,1],
      [2,2,2,2],
      [3,3,3,3]]

A target array with the same size Y

Y = [ [-1,-1,-1,-1],
      [-2,-2,-2,-2],
      [-3,-3,-3,-3]]

And an assigment array IDX:

IDX = [ [1,0,0,0],
        [0,0,1,0],
        [0,1,0,1]] 

I want to assign Y to X by IDX - Only assign where IDX==1 In this case, something like:

X[IDX] = Y[IDX]

will result in:

X = [ [-1,1,1,1],
      [2,2,-2,2],
      [3,-3,3,-3]]

How can this be done efficiently (not a for-loop) in numpy/pandas? Thx

2
  • 3
    IDX = IDX.astype(bool), and then just do it. Commented Jun 20, 2022 at 10:53
  • 3
    np.where(IDX==1, Y,X) use X , Y , IDX as numpy.array Commented Jun 20, 2022 at 10:53

1 Answer 1

2

If IDX is a NumPy array of Boolean type, and X and Y are NumPy arrays then your intuition works:

X = np.array(X)
Y = np.array(Y)
IDX = np.array(IDX).astype(bool)

X[IDX] = Y[IDX]

This changes X in place.

If you don't want to do all this type casting, or don't want to overwrite X, then np.where() does what you want in one go:

np.where(IDX==1, Y, X)
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.