按字母顺序,优雅地对数据降序然后按索引对 Pandas 系列进行排序

Ste*_*rpe 3 python sorting numpy python-3.x pandas

我正在寻找一种通过数据降序对熊猫系列进行排序的平滑方法,然后是索引升序。我一直在查看文档和 Stackoverflow,但找不到直接的方法。

该系列大约有 5000 个条目,是使用 NLTK 进行 tf-idf 分析的结果。

但是,下面我提供了一个非常小的数据样本来说明问题。

import pandas as pd

index = ['146tf150p', 'anytime', '645', 'blank', 'anything']
tfidf = [1.000000, 1.000000, 1.000000, 0.932702, 1.000000]

tfidfmax = pd.Series(tfidf, index=index)
Run Code Online (Sandbox Code Playgroud)

现在我只是将 Series 转换为 DataFrame,重置索引,进行排序然后设置索引,但我觉得这是一个很大的弯路。

frame = pd.DataFrame(tfidfmax , columns=['data']).reset_index().sort_values(['data','index'], ascending=[False, True]).set_index(['index'])
3.02 ms ± 102 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Run Code Online (Sandbox Code Playgroud)

我期待着您的建议!

jpp*_*jpp 5

您可以numpy.lexsort为此使用:

res = tfidfmax[np.lexsort((tfidfmax.index, -tfidfmax.values))]

print(res)

# 146tf150p    1.000000
# 645          1.000000
# anything     1.000000
# anytime      1.000000
# blank        0.932702
# dtype: float64
Run Code Online (Sandbox Code Playgroud)

请注意语法中的相反顺序:上面的代码首先按值降序排序,然后按索引升序排序。