Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - How to change values in numpy array

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...