Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

import numpy as np
a=np.array([[4,2,6],[3,6,5]])
b=np.array([3,5])

I want to update the numbers in "a" which are bigger than the numbers in "b" to np.nan. If they are smaller or equal i don't want it to be changed. I want to compare the first row of "a" to the first scalar of "b" and the second row of "a" to the second scalar of "b".

e.g.

a = array([[4, 2, 6],
           [3, 6, 5]])

the updated value should be:

array([[nan, 2, nan],
       [3, nan, 5]])

I've tried this:

for i in range(2):
     a[i]=np.where(a[i]<=b[i],a[i],np.nan)

But it doesn't work. HELP ME PLEASE!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can write so:

import numpy as np
a=np.array([[4,2,6],[3,6,5]])
b=np.array([3,5])

# shape in compared axis must be the same or one of their length must be equal 1
# in this case their shape is b(2,1) and a(2,3)

a = np.where(a <= b.reshape(b.shape[0],1), a, np.nan)
print(a)

but in more difficult cases I'm not sure, that it will work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...