gpt4 book ai didi

python - 对 Pandas Series 的数据进行排序,然后按字母顺序优雅地按索引排序

转载 作者:行者123 更新时间:2023-11-28 20:59:17 31 4
gpt4 key购买 nike

我正在寻找一种顺畅的方式来按数据降序对 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)

目前我只是将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)

期待您的建议!

最佳答案

您可以使用 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

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

关于python - 对 Pandas Series 的数据进行排序,然后按字母顺序优雅地按索引排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814881/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com