0

I am trying to mask some elements in an array such that a mathematical operation is not applied to these elements.

I ran this code

import numpy as np

inp = np.random.randn(5, 5)
c = np.random.randn(5,5)
mask = inp > 0


inp[mask] += c

print(inp)

but I got this error

ValueError: operands could not be broadcast together with shapes (25,) (5,5) (25,)

5
  • See numpy masked arrays Commented Apr 29, 2021 at 17:17
  • Have you checked the shape of input[mask] to see if it looks like you expect? Commented Apr 29, 2021 at 17:21
  • You can't add arrays of different shapes that are not broadcastable. Commented Apr 29, 2021 at 17:22
  • Also worth noting: Don't name variables the same as built-in functions, like input in your case would shadow the built-in input function Commented Apr 29, 2021 at 17:22
  • inp[mask] += c[mask] should work Commented Apr 29, 2021 at 20:43

1 Answer 1

1
inp += mask.astype(int) * c

# -- or simplified to:
inp += mask * c
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.