在 pandas 系列中查找元素的索引 [英] Find element's index in pandas Series

查看:100
本文介绍了在 pandas 系列中查找元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice)

即,我想要类似的东西:

I.e., I'd like something like:

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

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

Certainly, it is possible to define such a method with a loop:

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

print find(myseries, 7)

但我认为应该有更好的方法.有吗?

but I assume there should be a better way. Is there?

推荐答案

>>> myseries[myseries == 7]
3    7
dtype: int64
>>> myseries[myseries == 7].index[0]
3

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

Though I admit that there should be a better way to do that, but this at least avoids iterating and looping through the object and moves it to the C level.

这篇关于在 pandas 系列中查找元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆