按绝对值排序而不更改数据 [英] Sorting by absolute value without changing the data

查看:71
本文介绍了按绝对值排序而不更改数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种按特定列的绝对值对熊猫数据框进行排序的简单方法,但实际上并未更改数据框内的值.与sorted(df, key=abs)类似.因此,如果我有一个像这样的数据框:

I'm looking for a simple way to sort a pandas dataframe by the absolute value of a particular column, but without actually changing the values within the dataframe. Something similar to sorted(df, key=abs). So if I had a dataframe like:

    a   b
0   1   -3
1   2   5 
2   3   -1
3   4   2
4   5   -9

对'b'进行排序时所得到的排序数据看起来像:

The resultant sorted data when sorting on 'b' would look like:

    a   b
2   3   -1
3   4   2
0   1   -3
1   2   5 
4   5   -9

推荐答案

更新

由于 0.17.0 ordersort已被弃用(感谢@Ruggero Turra),您现在可以使用sort_values来实现:

Since 0.17.0 order and sort have been deprecated (thanks @Ruggero Turra), you can use sort_values to achieve this now:

In[16]:

df.reindex(df.b.abs().sort_values().index)
Out[16]: 
   a  b
2  3 -1
3  4  2
0  1 -3
1  2  5
4  5 -9

这篇关于按绝对值排序而不更改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆