numpy searchsorted 我做错了什么?

What am I doing wrong with numpy searchsorted?

numpy.searchsorted 的行为很有趣。以下测试失败:

import numpy as np

a = np.ma.masked_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
                        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
                        31, 32, 33, 0],
                       mask=[False, False, False, False, False, False, False,
                             False, False, False, False, False, False, False,
                             False, False, False, False, False, False, False,
                             False, False, False, False, False, False, False,
                             False, False, False, False, False,  True],
                       fill_value=0, dtype='uint8')

b = np.array([1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
              17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 33],
             dtype='uint8')

expected = np.array([0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,
                 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
                 28, 29, 32])

c = a.searchsorted(b)

np.testing.assert_array_equal(c, expected)

c 数组中的最后一项是 34,我不知道为什么。 但是一个类似的,它通过:

aa = np.ma.masked_array([1, 2, 3, 4, 0],
                        mask=[False, False, False, False, True],
                        fill_value=0, dtype='uint8')

bb = np.array([1, 3, 4], dtype='uint8')

expectedd = np.array([0, 2, 3])

cc = aa.searchsorted(bb)

np.testing.assert_array_equal(cc, expectedd)

numpy.array.searchsorted 文档中,其描述为:

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

np.searchsorted doesn't yet support masked arrays (see here 获取支持的方法列表)。

您可以通过手动索引 aa.mask 的逆来获得预期的结果,然后将结果作为第一个参数传递给 np.searchsorted:

c = np.searchsorted(a[~a.mask], b)

# or alternatively, a[~a.mask].searchsorted(b)

print(np.allclose(c, expected))
# True