在pandas序列数据结构中获取一个值的索引的代码是什么?
animals=pd.Series(['bear','dog','mammoth','python'],
index=['canada','germany','iran','brazil'])提取“长毛象”索引的代码是什么?
发布于 2018-12-31 06:20:10
您可以只使用布尔索引:
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数据结构,索引不一定是唯一的。
发布于 2018-12-31 07:03:31
您有两个选择:
1)如果您确保该值是唯一的,或者只想获取第一个值,请使用find函数。
find(animals, 'mammoth') # retrieves index of first occurrence of value2)如果你想让所有的索引都匹配这个值,就像@juanpa.arrivillaga的帖子一样。
animals[animals == 'mammoth'].index # retrieves indices of all matching values您还可以通过将上述语句视为列表来索引查找该值的任意数量的匹配项:
animals[animas == 'mammoth'].index[1] #retrieves index of second occurrence of value.https://stackoverflow.com/questions/53981868
复制相似问题