gpt4 book ai didi

python - Pandas 。如何在不更改索引的情况下对 DataFrame 进行排序?

转载 作者:行者123 更新时间:2023-12-02 16:25:20 24 4
gpt4 key购买 nike

df2 = pd.DataFrame({
"A": [26, 2, 3],
"B": [0, 7, 1],
"C": [7, 5, 4]
},
index=list('abc'))
df2

输出:

    A  B  C
a 26 0 7
b 2 7 5
c 3 1 4

df2.sort_values(['B', 'A'], ascending=[False, True]) 给出:

    A  B  C
b 2 7 5
c 3 1 4
a 26 0 7

带索引的列现在按新顺序打乱,但我希望它即使在排序后也保持不变。参数 ignore_index 只是设置从 0n-1 的索引。 sort_index 函数也没有帮助,因为索引可能不是按字典顺序排列的。

最佳答案

您可以在排序后添加索引:

df2 = df2.sort_values(['B', 'A'], ascending=[False, True]).reset_index(drop=True)
df2['index'] = ['a', 'b', 'c']
df2.set_index('index', inplace=True)

print(df2)

A B C
index
a 2 7 5
b 3 1 4
c 26 0 7

关于python - Pandas 。如何在不更改索引的情况下对 DataFrame 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64686916/

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