将不包含在np.where中的元素设置为np.nan [英] set the elements not included by np.where as np.nan

查看:253
本文介绍了将不包含在np.where中的元素设置为np.nan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将所有非7的元素设置为np.nan?

How can I set all the elements that are not 7 as np.nan?

import numpy as np
data  = np.array([[0,1,2,3,4,7,6,7,8,9,10], 
        [3,3,3,4,7,7,7,8,11,12,11],  
        [3,3,3,5,7,7,7,9,11,11,11],
        [3,4,3,6,7,7,7,10,11,11,11],
        [4,5,6,7,7,9,10,11,11,11,11]])

result = np.where(data==7) 
data[~result] = np.nan
print data

Traceback (most recent call last):
  File "M:\test.py", line 10, in <module>
    data[~result] = np.nan
TypeError: bad operand type for unary ~: 'tuple'

推荐答案

必须有更好的方法,但这是我现在能想到的最好的方法.制作所有np.nan的另一个数组,然后将result中索引处的值替换为实际值:

There must be a better way but this is the best I can think of right now. Make another array of all np.nan, and then replace the values at the indices in result with the real values:

data_nan = np.full(data.shape, np.nan)
data_nan[result] = data[result]
data = data_nan

如果要获取不在result中的所有索引的列表,则可以执行此操作,尽管我认为上述方法可能更好:

If you want to get a list of all indices that are not in result, you could do this, though I think the above is probably better:

inc = np.core.rec.fromarrays(result)
all_ind = np.core.rec.fromarrays(np.indices(data.shape).reshape(2,-1))
exc = np.setdiff1d(all_ind, inc)
data[exc['f0'], exc['f1']] = np.nan

这可以通过将每对索引转换为结构化数组的一个元素来进行,以便可以将它们作为集合元素与所有索引的相似数组进行比较.然后,我们对它们进行设置差异并得到其余的结果.

This works by turning each pair of indices into one element of a structured array, so that they can be compared as set elements to a similar array of all indices. Then we do the set difference of these and get the rest.

这篇关于将不包含在np.where中的元素设置为np.nan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆