从 natsort 创建一个新的熊猫索引列

问题描述

给定这个输入

df = pd.DataFrame(
                [["1 (2)","4"],["5 (3)","2"],["4 (2)",["1 (1)",["1 (2)","3"]],columns=["a","b"],)
    a       b
0   1 (2)   4
1   5 (3)   2
2   4 (2)   4
3   1 (1)   4
4   1 (2)   3

到达这个输出

expected =  pd.DataFrame(
                [["1 (2)","4",2],"2",0],1],4],"3",3]],"b","c"],)
  a        b   c
0   1 (2)   4   2
1   5 (3)   2   0
2   4 (2)   4   1
3   1 (1)   4   4
4   1 (2)   3   3

其中 c 列包含 a 列中项目的顺序,这是 natsorted。我需要这样做:

indexes_human_sorted = natsort.index_humansorted(df["a"],reverse=True) # [1,2,4,3] gets the values in order x[1],x[2],x[0] etc.
for i,x in enumerate(indexes_human_sorted):
    df.loc[x,"c"] = i

    a       b  c
0   1 (2)   4   2.0
1   5 (3)   2   0.0
2   4 (2)   4   1.0
3   1 (1)   4   4.0
4   1 (2)   3   3.0

我认为对索引的循环(速度很慢)应该是不必要的,而且我认为我错过了 natsort 的一些技巧。

解决方法

我相信您可以使用 np.argsort

df['c'] = np.argsort(natsort.index_humansorted(df['a'],reverse=True))

print(df)

       a  b  c
0  1 (2)  4  2
1  5 (3)  2  0
2  4 (2)  4  1
3  1 (1)  4  4
4  1 (2)  3  3