Python 找到非数值索引值的数值位置
考虑下面的系列Python 找到非数值索引值的数值位置,python,numpy,pandas,Python,Numpy,Pandas,考虑下面的系列s: s = pd.Series(np.arange(18, 0, -3), list('ABCDEF')) s A 18 B 15 C 12 D 9 E 6 F 3 dtype: int32 我想得到'D' 这就行了,但我想我们都同意这很恶心: s.reset_index().index.to_series()[s.reset_index().iloc[:, 0] == 'D'].iloc[0] 使用- 或者像这样使用这个方法- s
s
:
s = pd.Series(np.arange(18, 0, -3), list('ABCDEF'))
s
A 18
B 15
C 12
D 9
E 6
F 3
dtype: int32
我想得到'D'
这就行了,但我想我们都同意这很恶心:
s.reset_index().index.to_series()[s.reset_index().iloc[:, 0] == 'D'].iloc[0]
使用-
或者像这样使用这个方法-
s.index.searchsorted('D')
您可以使用:
我很高兴你提供了numpy解决方案,然后找到了pandas解决方案;-)。你应该在我的帖子中添加numpy标签。@piRSquared这就是回答问题的妙处,特别是对于我并不熟悉的标签!;)看起来像是内置的这样的任务,可爱!注意:如果索引中有多个“D”,则返回一个数组!
s.index.searchsorted('D')
print(s.index.get_loc('D'))
3
m = s.index == 'D'
idx = m.argmax() if m.any() else None