简体   繁体   中英

Masking values in numpy array

I have the foll. code in numpy:

mask_cntr = np.copy(map_ccodes)
mask_cntr[mask_cntr == cntr] = 1.0
mask_cntr[mask_cntr != 1.0] = 0.0

Here, I am copying the 2D array map_ccodes to mask_cntr , and assigning the values that equal cntr in that array to 1.0 , and all others to 0.0 .

Is there a faster and more pythonic way to do this in numpy?

np.where函数接受条件并根据条件为True或False返回输出:

np.where(mask_cntr == cntr, 1.0, 0.0)

Try

mask_cntr = 1.0*(map_ccodes==cntr)

I am assuming that cntr == 1 from your code?

Why do you need a separate mask anyway? You can always use the map_ccodes==cntr argument anywhere ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM