gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:57 29 4
gpt4 key购买 nike

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com