我有一个数据框,如下所示:
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
s的列是索引,我希望将其排序如下:
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)
但它不起作用。
这怎么办?
答案 0 :(得分:2)
您可以尝试以下操作:
使用series.str.extract()
和\d+
仅提取数字,仅提取数字值,然后提取sort_values()
,最后使用df.reindex()
中的索引重新索引数据框。
\ d:0到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()))