如何获取Pandas系列中的值的索引

2024-06-26 04:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

获取pandas系列数据结构中某个值的索引的代码是什么?。在

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

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


Tags: 代码数据结构pandasindexseriespdiranbear
2条回答

您有两种选择:

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

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

2)如果您希望获得与该值匹配的所有索引,则根据@胡安帕.阿里维拉加的职位。在

^{pr2}$

您还可以通过将上述语句视为列表来索引查找值的任何数字:

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

您只需使用布尔索引:

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')

注意,对于pandas数据结构,索引并不一定是唯一的。在

相关问题 更多 >