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

2024-05-23 22:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,如下所示:

              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

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

            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)

但它不起作用

如何做到这一点


Tags: 数据排序stepstepssortmaxstep1step2
1条回答
网友
1楼 · 发布于 2024-05-23 22:36:51

您可以尝试以下方法: 只提取数字使用^{}\d+只提取数值,然后sort_values(),最后使用^{}中的索引来重新索引数据帧

\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

另一种方法是使用^{}

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

相关问题 更多 >