我知道这是一个非常基本的问题,但出于某种原因,我找不到答案。我怎样才能得到在python熊猫系列的某些元素的索引?(第一种情况就足够了)

例如,我想要这样的东西:

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

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

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

print find(myseries, 7)

但我想应该有更好的办法。是吗?


当前回答

如果你使用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)

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

(array([3], dtype=int64),)

其他回答

另一种方法是:

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

list(s).index(7)

返回: 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

df。索引方法将帮助您找到确切的行号

my_fl2=(df['ConvertedCompYearly'] == 45241312 )
print (df[my_fl2].index)

   
Name: ConvertedCompYearly, dtype: float64
Int64Index([66910], dtype='int64')

如果你使用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)

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

(array([3], dtype=int64),)

Pandas有内置的类Index和一个名为get_loc的函数。这个函数将返回

索引(元素索引) 切片(如果指定的数字是顺序的) 数组(如果数字在多个下标处,则为bool数组)

例子:

import pandas as pd

>>> mySer = pd.Series([1, 3, 8, 10, 13])
>>> pd.Index(mySer).get_loc(10)  # Returns index
3  # Index of 10 in series

>>> mySer = pd.Series([1, 3, 8, 10, 10, 10, 13])
>>> pd.Index(mySer).get_loc(10)  # Returns slice
slice(3, 6, None)  # 10 occurs at index 3 (included) to 6 (not included)


# If the data is not in sequence then it would return an array of bool's.
>>> mySer = pd.Series([1, 10, 3, 8, 10, 10, 10, 13, 10])
>>> pd.Index(mySer).get_loc(10)
array([False, True, False, False, True, True, False, True])

也有很多其他的选择,但我发现这对我来说很简单。

另一种还没有提到的方法是tolist方法:

myseries.tolist().index(7)

应该返回正确的索引,假设该值存在于Series中。