1

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説明は次のように述べています。

v の対応する要素がインデックスの前に挿入された場合、a の順序が保持されるように、並べ替えられた配列 a のインデックスを見つけます。

4

1 に答える 1