在pandas系列中查找元素的索引

sas*_*llo 126 python pandas

我知道这是一个非常基本的问题,但由于某种原因,我找不到答案.如何在python pandas中获取Series的某个元素的索引?(第一次出现就足够了)

即,我想要像:

import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
print myseries.find(7) # should output 3
Run Code Online (Sandbox Code Playgroud)

当然,可以用循环定义这样的方法:

def find(s, el):
    for i in s.index:
        if s[i] == el: 
            return i
    return None

print find(myseries, 7)
Run Code Online (Sandbox Code Playgroud)

但我认为应该有更好的方法.在那儿?

Vik*_*kez 170

>>> myseries[myseries == 7]
3    7
dtype: int64
>>> myseries[myseries == 7].index[0]
3
Run Code Online (Sandbox Code Playgroud)

虽然我承认应该有更好的方法来做到这一点,但这至少可以避免迭代和循环遍历对象并将其移动到C级别.

  • 这里的问题是它假设被搜索的元素实际上在列表中.这是一个无赖熊猫似乎没有内置的查找操作. (11认同)
  • 仅当您的序列具有顺序整数索引时,此解决方案才有效。如果您的系列索引按日期时间排序,则此方法无效。 (3认同)

Jef*_*eff 35

转换为索引,您可以使用 get_loc

In [1]: myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])

In [3]: Index(myseries).get_loc(7)
Out[3]: 3

In [4]: Index(myseries).get_loc(10)
KeyError: 10
Run Code Online (Sandbox Code Playgroud)

重复处理

In [5]: Index([1,1,2,2,3,4]).get_loc(2)
Out[5]: slice(2, 4, None)
Run Code Online (Sandbox Code Playgroud)

如果非连续返回,将返回一个布尔数组

In [6]: Index([1,1,2,1,3,2,4]).get_loc(2)
Out[6]: array([False, False,  True, False, False,  True, False], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

内部使用哈希表,速度很快

In [7]: s = Series(randint(0,10,10000))

In [9]: %timeit s[s == 5]
1000 loops, best of 3: 203 µs per loop

In [12]: i = Index(s)

In [13]: %timeit i.get_loc(5)
1000 loops, best of 3: 226 µs per loop
Run Code Online (Sandbox Code Playgroud)

正如Viktor所指出的,创建索引会产生一次性创建开销(当您实际使用索引执行某些操作时会产生这种开销,例如is_unique)

In [2]: s = Series(randint(0,10,10000))

In [3]: %timeit Index(s)
100000 loops, best of 3: 9.6 µs per loop

In [4]: %timeit Index(s).is_unique
10000 loops, best of 3: 140 µs per loop
Run Code Online (Sandbox Code Playgroud)


Bil*_*ill 17

我对这里的所有答案印象深刻。这不是一个新答案,只是试图总结所有这些方法的时间。我考虑了具有 25 个元素的系列的情况,并假设了索引可以包含任何值的一般情况,并且您希望索引值对应于接近系列末尾的搜索值。

以下是使用 Python 3.7 和 Pandas 版本 0.25.3 在 2013 年 MacBook Pro 上的速度测试。

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Run Code Online (Sandbox Code Playgroud)

@Jeff 的答案似乎是最快的——尽管它不处理重复项。

更正:对不起,我错过了一个,@Alex Spangher 使用列表索引方法的解决方案是迄今为止最快的。

更新:添加了@EliadL 的答案。

希望这可以帮助。

令人惊讶的是,如此简单的操作需要如此复杂的解决方案,而且许多解决方案如此缓慢。在某些情况下超过半毫秒才能在 25 的系列中找到一个值。


Alo*_*lon 10

In [92]: (myseries==7).argmax()
Out[92]: 3
Run Code Online (Sandbox Code Playgroud)

如果您事先知道7,那么这是有效的.您可以使用(myseries == 7).any()进行检查

另一种方法(非常类似于第一个答案)也考虑了多个7(或没有)

In [122]: myseries = pd.Series([1,7,0,7,5], index=['a','b','c','d','e'])
In [123]: list(myseries[myseries==7].index)
Out[123]: ['b', 'd']
Run Code Online (Sandbox Code Playgroud)

  • 小心,如果没有元素匹配此条件,`argmax` 仍将返回 0(而不是出错)。 (2认同)

Ale*_*her 7

另一种方法来做到这一点,虽然同样不令人满意的是:

s = pd.Series([1,3,0,7,5],index=[0,1,2,3,4])

list(s).index(7)
Run Code Online (Sandbox Code Playgroud)

回报:3

使用我正在使用的当前数据集进行时间测试(认为它是随机的):

[64]:    %timeit pd.Index(article_reference_df.asset_id).get_loc('100000003003614')
10000 loops, best of 3: 60.1 µs per loop

In [66]: %timeit article_reference_df.asset_id[article_reference_df.asset_id == '100000003003614'].index[0]
1000 loops, best of 3: 255 µs per loop


In [65]: %timeit list(article_reference_df.asset_id).index('100000003003614')
100000 loops, best of 3: 14.5 µs per loop
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 6

如果您使用 numpy,您可以获得找到您的值的 indecies 数组:

import numpy as np
import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
np.where(myseries == 7)
Run Code Online (Sandbox Code Playgroud)

这将返回一个包含 indecies 数组的单元素元组,其中 7 是 myseries 中的值:

(array([3], dtype=int64),)
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以使用Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 
Run Code Online (Sandbox Code Playgroud)

  • 这似乎只返回找到最大元素的索引,而不是像所问的问题那样返回特定的“某个元素的索引”。 (6认同)