这在 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
尚不支持掩码数组( see here 获取受支持方法的列表)。
您可以通过使用 a.mask
的逆值手动索引 a
来获得预期结果,然后将结果作为第一个参数传递给 np.searchsorted
:
c = np.searchsorted(a[~a.mask], b)
# or alternatively, a[~a.mask].searchsorted(b)
print(np.allclose(c, expected))
# True
关于python - 我对 numpy searchsorted 做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36896855/