簡體   English   中英

如何有效獲取列表中所有項目的索引中的序數位置

[英]How do we get the ordinal positions within an index for all items in a list efficiently

考慮唯一的 pd.Index idx和索引列表lst

idx = pd.Index(list('abcdefg'))
lst = list('bdf')

我們可以通過idx.get_loc('b')獲得'b'的序數位置。

我們如何在所有項目的序號位置lst有效?

idx.get_loc(lst)不起作用:

TypeError: '['b', 'd', 'f']' is an invalid key
In [317]: timeit (np.array(idx)[:,None]==np.array(lst)).argmax(0)
10000 loops, best of 3: 35.4 µs per loop
In [318]: timeit [idx.index(i) for i in lst]
100000 loops, best of 3: 4.78 µs per loop
In [321]: timeit np.where(np.in1d(idx,lst))
10000 loops, best of 3: 53.1 µs per loop

我們可以使用np.searchsorted

idx.searchsorted(lst)

如果idx未排序,則需要對其使用sorter參數。

使lst為numpy數組,然后與廣播進行比較。 然后使用argmax識別位置。

(idx.values[:, None] == np.array(lst)).argmax(0)

array([1, 3, 5])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM