gpt4 book ai didi

python - 如何根据数字部分对数据框的索引进行排序?

转载 作者:行者123 更新时间:2023-12-01 00:53:18 25 4
gpt4 key购买 nike

我有一个数据框如下:

              Max
step1 2.001953125
step19 86.669921875
step2 2.001953125
step24 2.24609375
step25 2.001953125
step26 2.001953125
step27 2.001953125
step5 46.97265625

包含步骤的列是索引,我想将其排序如下:

            Max
step1 2.001953125
step2 2.001953125
step5 46.97265625
step19 86.669921875
step24 2.24609375
step25 2.001953125
step26 2.001953125
step27 2.001953125

我尝试这样做:

steps_max.sort_index(inplace = True)

但它不起作用。

如何做到这一点?

最佳答案

您可以尝试以下方法:使用 series.str.extract() 仅提取数字和 \d+ 仅提取数值,然后 sort_values(),最后在 df.reindex() 中使用该索引重新索引数据框。

\d : Any numeric digit from 0 to 9.

i=df.index.to_series().str.extract('(\d+)',expand=False).astype(float).sort_values().index
df.reindex(i)
<小时/>
              Max
step1 2.001953
step2 2.001953
step5 46.972656
step19 86.669922
step24 2.246094
step25 2.001953
step26 2.001953
step27 2.001953

另一种方法是使用natsort :

import natsort as ns
df.reindex(ns.natsorted(df.index))
#df.reindex(sorted(ns.natsorted(df.index), key=lambda x: not x.isdigit()))

关于python - 如何根据数字部分对数据框的索引进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413847/

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