0

I have an array that specifies how many elements along the last axis of a matrix I want to change to 0. How do I do this efficiently?

x = np.ones((4, 4, 10))
change_to_zeros = np.random.randint(10, size=(4, 4))
# change_to_zeros = 
# [[2 1 6 8]
# [4 0 4 8]
# [7 6 6 2]
# [4 0 7 1]]

Now what I want to do is something like x[:, :, :change_to_zeros] = 0 - for example for the first element of change_to_zeros, I have change_to_zeros[0, 0] = 2 so I want to change the first (or last, or whatever) 2 elements along the last axis of x (length 10) to 0.

Clarification: For example at x[0, 0, :] I have ones with length 10. I want to change 2 of these (change_to_zeros[0, 0] = 2) to 0, keeping the rest with ones.

2
  • 1
    Can you be more clear on what your intended output must be Commented Jul 24, 2018 at 19:35
  • Sorry for not being clear. For example at x[0, 0, :] I have ones with length 10. I want to change 2 of these (change_to_zeros[0, 0] = 2) to 0, keeping the rest with ones. Commented Jul 24, 2018 at 19:37

1 Answer 1

1

You can create a boolean array (same shape as x) with change_to_zeros[:,:,None] > np.arange(x.shape[-1]) and then assign zero to trues:

x[change_to_zeros[:,:,None] > np.arange(x.shape[-1])] = 0

Check results:

change_to_zeros[0,0]
# 2

x[0,0]
# array([ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

change_to_zeros[0,2]
# 7

x[0,2]
# array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.])
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.