4

Consider the series s below:

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

I want to get the numeric position of 'D'

This will do it, but I think we can all agree this is gross:

s.reset_index().index.to_series()[s.reset_index().iloc[:, 0] == 'D'].iloc[0]
Divakar
  • 218,885
  • 19
  • 262
  • 358
piRSquared
  • 285,575
  • 57
  • 475
  • 624

3 Answers3

8

You can use Index.get_loc:

print(s.index.get_loc('D'))
3
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
4

Use np.searchsorted -

np.searchsorted(s.index.values,'D')

Or use the method, like so -

s.index.searchsorted('D')
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • I love that you provided the numpy solution then found the pandas solution afterwards ;-). You should add the numpy tag to my post. – piRSquared Jul 18 '16 at 16:44
  • 1
    @piRSquared That's the beauty of answering questions, specially with tags that I am really not familiar with! ;) – Divakar Jul 18 '16 at 16:45
3
m = s.index == 'D'
idx = m.argmax() if m.any() else None
Alex
  • 18,484
  • 8
  • 60
  • 80