2009年11月14日土曜日

リストの要素の近い値のインデックスを返す。numpy searchsorted()

numpy の関数 searchsorted() は、本来 リストに要素を追加したい場合に、そのリストの要素の順序を崩さないように追加できる、インデックスを返す。

>>> tt =[1,2,3,4,5,6,8,9]
>>> np.searchsorted(tt,7)
6
>>> np.searchsorted(tt,2)
1
>>> np.searchsorted(tt,2, side="right")
2
-----------------------------------------------------
numpy.searchsorted(a, v, side='left')

Find indices where elements should be inserted to maintain order.

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.

Parameters
----------
a : 1-D array_like of shape (N,)
Input array, sorted in ascending order.
v : array_like
Values to insert into `a`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given. If
'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `a`).