无法按值降序排序熊猫数据框,然后按升序字母排序

时间:2020-08-20 17:32:19

标签: python-3.x pandas sorting alphabetical-sort

我的数据帧df的一部分就是这样,所以您可以重现它。

data ={'feature_name': ['nite', 'thank', 'ok', 'havent', 'done', 'beverage', 'yup', 'lei','thanx', 'okie', '146tf150p', 'home', 'too', 'anytime',
       'where', '645', 'er', 'tick', 'blank'], 'values':[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.98, 0.98] }
df = pd.DataFrame(data)
df.set_index('feature_name',inplace=True)
dfs=df.sort_index(ascending=True).sort_values(by = ['values'], ascending=False)
dfs

我的输出是这个。

            values
feature_name    
146tf150p   1.00
645         1.00
where       1.00
too         1.00
thanx       1.00
thank       1.00
okie        1.00
ok          1.00
nite        1.00
lei         1.00
home        1.00
havent      1.00
er          1.00
done        1.00
beverage    1.00
anytime     1.00
yup         1.00
blank       0.98
tick        0.98

我不太明白为什么它不是这样?它确实应该可以工作,但不能按预期工作。


146tf150p   1.00
645         1.00
anytime     1.00
beverage    1.00
done        1.00
er          1.00
haven't     1.00
home        1.00
...

我该如何解决?

1 个答案:

答案 0 :(得分:1)

摆脱set_index并在值和feature_name上都使用sort_values

print (df.sort_values(by = ['values',"feature_name"], ascending=(False, True)))

   feature_name  values
10    146tf150p    1.00
15          645    1.00
13      anytime    1.00
5      beverage    1.00
4          done    1.00
16           er    1.00
3        havent    1.00
11         home    1.00
7           lei    1.00
0          nite    1.00
2            ok    1.00
9          okie    1.00
1         thank    1.00
8         thanx    1.00
12          too    1.00
14        where    1.00
6           yup    1.00
18        blank    0.98
17         tick    0.98