Home > Enterprise >  Can I put a condition for y-index in numpy.where?
Can I put a condition for y-index in numpy.where?

Time:08-16

I have a 2D numpy array taken from a segmentation. Therefore, it's an image like the one in the right:

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwYeYOHk0xUJ6vBd_g8Xn1LxMON0g2qHpf_TPJx6h7IM5nG2OXeKtDuCcjgN9mqFtLB5c&usqp=CAU

The colours you see means that each value of my array can only have a value in a limit range (e.g., green is 5, orange is 7...). Now I would like to change all the cells that contains a 5 (green) and its y-coordinate is up to a value I want (e.g. only apply the later condition up to row 400). What's the most optimized algorithm to do this?

I guess that you can use something like:

np.where(myarray == 5, myarray, valueIwant)

but I will need to apply the condition for y-index...

CodePudding user response:

Your current example seems to be misaligned with what you want:

a = np.array([1, 1, 2, 2, 3, 3])
np.where(a==2, a, 7)

produces:

array([7, 7, 2, 2, 7, 7])

If you want to replace 2 with some other value:

array([1, 1, 7, 7, 3, 3])

you can do this:

np.where(a==2, 7, a)

or

a[a==2] = 7

To replace only up to a certain value:

sub_array = a[:3]

sub_array[sub_array==2] = 7
a
array([1, 1, 7, 2, 3, 3])
  • Related