python 在numpy中,调用MA.masked_where和MA.masked_array有什么区别?

mwg9r5ms  于 2023-02-28  发布在  Python
关注(0)|答案(2)|浏览(130)

调用masked_array(类构造函数)和masked_where函数似乎做的是完全相同的事情,都是在给定数据和掩码值的情况下构造一个numpy掩码数组。

>>> import numpy as np
>>> import numpy.ma as MA

>>> vals = np.array([0,1,2,3,4,5])
>>> cond = vals > 3

>>> vals
array([0, 1, 2, 3, 4, 5])

>>> cond
array([False, False, False, False,  True,  True], dtype=bool)

>>> MA.masked_array(data=vals, mask=cond)
masked_array(data = [0 1 2 3 -- --],
             mask = [False False False False  True  True],
       fill_value = 999999)

>>> MA.masked_where(cond, vals)
masked_array(data = [0 1 2 3 -- --],
             mask = [False False False False  True  True],
       fill_value = 999999)

masked_array也支持copymasked_where的可选参数(它唯一的文档可选参数),所以我没有看到任何masked_where独有的选项。虽然相反的情况不成立(例如masked_where不支持dtype),但我不明白masked_where作为一个单独函数的用途。

js4nwp54

js4nwp541#

masked_array是MaskedArray类的别名。当您使用它时,没有参数验证。
masked_where是一个函数,用于创建MaskedArray的示例,以检查参数。

def masked_where(condition, a, copy=True):
    """[docstring]"""
    # Make sure that condition is a valid standard-type mask.
    cond = make_mask(condition, shrink=False)
    a = np.array(a, copy=copy, subok=True)

    (cshape, ashape) = (cond.shape, a.shape)
    if cshape and cshape != ashape:
        raise IndexError("Inconsistent shape between the condition and the input"
                         " (got %s and %s)" % (cshape, ashape))
    if hasattr(a, '_mask'):
        cond = mask_or(cond, a._mask)
        cls = type(a)
    else:
        cls = MaskedArray
    result = a.view(cls)
    # Assign to *.mask so that structured masks are handled correctly.
    result.mask = _shrink_mask(cond)
    # There is no view of a boolean so when 'a' is a MaskedArray with nomask
    # the update to the result's mask has no effect.
    if not copy and hasattr(a, '_mask') and getmask(a) is nomask:
        a._mask = result._mask.view()
    return result
hmae6n7t

hmae6n7t2#

您的评论:
如果我用形状不一致的值和掩码数组调用它们,在这两种情况下都会得到相同的错误消息。
如果不详细说明有什么不同,我想我们帮不了你。
例如,如果我尝试明显的不一致性,即长度,我得到不同的错误消息:

In [121]: np.ma.masked_array(vals, cond[:-1])
MaskError: Mask and data not compatible: data size is 5, mask size is 4.
In [122]: np.ma.masked_where(cond[:-1], vals)
IndexError: Inconsistent shape between the condition and the input (got (4,) and (5,))

从Corralian显示的代码中可以明显看出对where消息的测试。
Masked_Array类定义具有以下测试:

# Make sure the mask and the data have the same shape
        if mask.shape != _data.shape:
            (nd, nm) = (_data.size, mask.size)
            if nm == 1:
                mask = np.resize(mask, _data.shape)
            elif nm == nd:
                mask = np.reshape(mask, _data.shape)
            else:
                msg = "Mask and data not compatible: data size is %i, " + \
                      "mask size is %i."
                raise MaskError(msg % (nd, nm))

只有当形状通过了where测试,但被类的测试捕获时,我才期望得到相同的消息。如果是这样,在完整的错误追溯中应该是显而易见的。
下面是一个在where上失败的示例,但它通过了base。

In [138]: np.ma.masked_where(cond[:,None],vals)
IndexError: Inconsistent shape between the condition and the input (got (5, 1) and (5,))
In [139]: np.ma.masked_array(vals, cond[:,None])
Out[139]: 
masked_array(data=[--, 1, --, 3, --],
             mask=[ True, False,  True, False,  True],
       fill_value=999999)

基类可以处理condshape不同,但与size(元素总数)匹配的情况。它尝试对其进行整形。标量cond通过这两种情况,尽管确切的测试不同。
根据我对代码的阅读,我无法想象有什么差异可以通过where,但不能通过base。
所有的掩码数组代码都是python可读的(参见另一个答案的链接)。虽然有一个基类定义,但有许多构造函数或帮助函数,正如where文档所阐明的那样。我不会太担心使用哪个函数,特别是如果你不想突破逻辑界限的话。
掩码数组虽然长期以来一直是numpy的一部分,但并没有得到很大的使用,至少从SO问题的相对缺乏来看是这样。我怀疑pandas在处理可能有缺失值的数据(例如时间序列)时已经在很大程度上取代了它。

相关问题