简体   繁体   English

在numpy数组中查找缺失值

[英]Finding missing values in a numpy array

Alright, extreme rookie question here. 好吧,极端的菜鸟问题在这里。 In my program, I generate a 2D numpy array, some of whom's entries are missing (not the "nan" kind of nonexistant, but the "None" kind, or NoneType). 在我的程序中,我生成了一个2D numpy数组,其中一些条目缺失(不是“nan”类型的nonxistant,而是“None”类,或NoneType)。 I'd like to put a mask over these entries, but I seem to be having some trouble doing so. 我想在这些条目上加上一个掩码,但我似乎遇到了一些麻烦。 Ordinarily, to mask over, say, all entries with value 2, I'd do 通常,为了掩盖所有值为2的条目,我会这样做

A = np.ma.masked_where(A[A==2], A) A = np.ma.masked_where(A [A == 2],A)

In this case, that doesn't seem to work no matter what I try for the first parameter. 在这种情况下,无论我尝试第一个参数,这似乎都不起作用。 Thoughts? 思考?

Since you have -- entries in your array, I guess that it means that they are already masked: 既然你有--数组中的条目,我想这意味着它们已经被屏蔽了:

>>> m = ma.masked_where([True, False]*5, arange(10))
>>> print m
[-- 1 -- 3 -- 5 -- 7 -- 9]

So, I would say that your entries are already masked and that you can directly use your array. 所以,我会说你的条目已被屏蔽,你可以直接使用你的数组。

If you want to create an array that only contains the non-masked value, you can do 如果要创建仅包含非屏蔽值的数组,则可以执行此操作

>>> m[~m.mask]
[1 3 5 7]

where m is your masked array. 其中m是你的蒙面数组。

If you want to have the list of masked values, you can simply select the other values: 如果要获取屏蔽值列表,只需选择其他值:

>>> m[m.mask]
[0 2 4 6 8]

Note that the missing values are not None, but are the original values, generally. 请注意,缺失值不是 None,而是一般的原始值。 In fact, an array of integers cannot contain None. 实际上,整数数组不能包含None。

If you want the indices of the masked values, you can do: 如果你想要掩码值的索引,你可以这样做:

>>> numpy.nonzero(m.mask)

The documentation of numpy.nonzero() describes how its result must be interpreted. numpy.nonzero()文档描述了如何解释其结果。

To find the elements in a numpy array that are None, you can use numpy.equal. 要在numpy数组中查找None的元素,可以使用numpy.equal。 Here's an example: 这是一个例子:

import numpy as np
import MA

x = np.array([1, 2, None])

print np.equal(x, None)
# array([False, False,  True], dtype=bool)

# to get a masked array
print MA.array(x, mask=np.equal(x,None))
# [1 ,2 ,-- ,]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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