如何获取熊猫系列中的值的索引

时间:2018-12-30 22:15:20

标签: python pandas

在熊猫系列数据结构中获取值索引的代码是什么?

animals=pd.Series(['bear','dog','mammoth','python'], 
                  index=['canada','germany','iran','brazil'])

提取“猛mm象”索引的代码是什么?

2 个答案:

答案 0 :(得分:0)

您可以只使用布尔索引:

In [8]: animals == 'mammoth'
Out[8]:
canada     False
germany    False
iran        True
brazil     False
dtype: bool

In [9]: animals[animals == 'mammoth'].index
Out[9]: Index(['iran'], dtype='object')

请注意,对于熊猫数据结构,索引不一定是唯一的。

答案 1 :(得分:0)

您有两个选择:

1)如果您确定该值是唯一的,或者只是想获取第一个值,请使用find函数。

find(animals, 'mammoth') #  retrieves index of first occurrence of value

2)如果您想获取所有与该值匹配的索引,请按照@ juanpa.arrivillaga的帖子进行。

animals[animals == 'mammoth'].index # retrieves indices of all matching values

您也可以通过将上面的语句作为列表来索引查找该值出现的任何数字:

animals[animas == 'mammoth'].index[1] #retrieves index of second occurrence of value.
相关问题