是否有一个 pandas 函数可以给我一个系列的排序位置?

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

我想要一个函数,它可以在 pandas Series 对象中为我提供一个元素的索引(如果 Series 已排序)。我做了以下实现:

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

但感觉有点基础。例如,这样的事情对于计算分位数是必要的。所以我希望有一种更简单的方法来实现这一目标成为图书馆的一部分。在 Pandas 中可以轻松获得类似的东西吗?

使用argsort获取排序顺序:

示例:

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

输出:

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

rank如果你更想要排名:

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

输出:

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