[英]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
使lst
為numpy數組,然后與廣播進行比較。 然后使用argmax
識別位置。
(idx.values[:, None] == np.array(lst)).argmax(0)
array([1, 3, 5])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.