Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

locate the numeric position of a non numeric index value

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]
like image 215
piRSquared Avatar asked Dec 06 '22 17:12

piRSquared


2 Answers

You can use Index.get_loc:

print(s.index.get_loc('D'))
3
like image 110
jezrael Avatar answered Dec 24 '22 18:12

jezrael


Use np.searchsorted -

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

Or use the method, like so -

s.index.searchsorted('D')
like image 30
Divakar Avatar answered Dec 24 '22 17:12

Divakar