sunheng
sunheng

Reputation: 65

How to get the sequence number of an index in pandas Series?

For example, I created a Series

x = pd.Series({'a': 10, 'b': 20, 'c': 30})

I would like to get the sequence number of x for index 'b', which should be 1. How do I do it?

I can certainly create a data frame to add a new sequence column [0,1,2] into x. And obtain the sequence number using data frame. For example, this works:

y = pd.DataFrame({'origin':x, 'seq':range(3)})
print(y.loc['b', 'seq'])     # Get 1.

This is a pretty ugly solution. There should be a function of Series doing that. But I did not find one.

Upvotes: 0

Views: 985

Answers (1)

Corralien
Corralien

Reputation: 120409

Use get_loc. From documentation:

Get integer location, slice or boolean mask for requested label.

>>> x.index.get_loc('b')
1

Upvotes: 1

Related Questions