python - 我对 numpy searchsorted 做错了什么?

标签 python numpy binary-search masked-array

这在 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/

相关文章:

python - 来自 sklearn 的 train_test_split 的 "Stratify"参数无法正常工作?

python - FFmpeg:组合了4个mp4视频的output.mp4不能保持原来的帧率

python - 如何连接两个 pandas 数据框中具有不同索引和非唯一键的列

python - python中用于计算最小范数解或从伪逆获得的解的最准确方法是什么?

python - 如果我们使用索引矩阵,是否需要在 Theano 中使用 flatten 和 reshape?

python - 将 pandas 数据框字符串条目拆分(分解)为单独的行

python - 查找两个排序数组的中位数。是否可以消除一些不平等检查?

java - while 循环不会以迭代二分查找结束

python - 通过 USB/串口连接到 Python 中的 Newport CONEX-PP 运动 Controller

java - 如何在降序排列的数组中进行二分查找?