这在 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
文档中,它的描述说:
找到排序数组 a 中的索引,这样,如果 v 中的相应元素插入到索引之前,则 a 的顺序将被保留。