Home > database >  Is there a pandas function to give me the ordering positions of a series?
Is there a pandas function to give me the ordering positions of a series?

Time:05-25

I want a function that would give me the index of an element in a pandas Series object if the Series was sorted. I made the following implementation:

def series_ordering(series):
    positions = series.reset_index(drop=True, inplace=False).sort_values().index
    return pd.Series(positions, index=series.index)

but it feels kind of basic. Something like this is necessary for computing quantiles for example. So I would expect an easier way to achieve this to be part of the library. Is something like this easily available in Pandas?

CodePudding user response:

Use argsort to get the sorting order:

Example:

pd.Series([2,3,1,4,0]).argsort()

output:

0    4
1    2
2    0
3    1
4    3
dtype: int64

Or rank if you rather want the rank:

pd.Series([2,3,1,4,0]).rank(method='dense').sub(1).convert_dtypes()

output:

0    2
1    3
2    1
3    4
4    0
dtype: Int64
  • Related