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

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

问题描述

我正在寻找一种通过特定列的绝对值排序熊猫数据帧的简单方法,但实际上并不更改数据帧中的值。有些类似于 sorted(df,key = abs)。所以如果我有一个数据框架,如:

  ab 
0 1 -3
1 2 5
2 3 -1
3 4 2
4 5 -9

在'b'排序时得到的排序数据将如下所示:

  ab 
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9


解决方案

一个笨重的方法是临时添加 abs 列b的值,然后 sort 使用该列,然后 drop 它:

 在[162]中:
df ['sort'] = df.b.abs()
df.sort(columns ='sort')drop('sort',axis = 1)

出[162]:
ab
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9

另一种方法是查看 abs 值'b',调用 sort ,然后调用 reindex 传递系列的索引:

 在[176]中:
t = df.b.abs()
t.sort()
df.reindex(t.index)

输出[176]:
ab
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9

编辑



以上可以作为单行:

 在[179]中:
df.reindex(df.b.abs()。sort(inplace = False).index)

输出[179]:
ab
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9

sort 默认情况下为 inplace =真的code>如此明确地传递 inplace = False 将返回系列。



另一个编辑



感谢master @Jeff这个未知的方法(对我来说),你可以调用 order abs 导致更干净的代码:

 在[31]中: 
df.reindex(df.b.abs()。order()。index)

输出[31]:
ab
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9


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

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

解决方案

One clunky method would be to temporarily add the abs value of column b, then sort using that column and then drop it:

In [162]:
df['sort'] = df.b.abs()
df.sort(columns='sort').drop('sort', axis=1)

Out[162]:
   a  b
2  3 -1
3  4  2
0  1 -3
1  2  5
4  5 -9

An alternative would be to take a view of the abs values of 'b', call sort on it and then call reindex passing the index of the series:

In [176]:
t = df.b.abs()
t.sort()
df.reindex(t.index)

Out[176]:
   a  b
2  3 -1
3  4  2
0  1 -3
1  2  5
4  5 -9

EDIT

The above can be done as a one-liner:

In [179]:
df.reindex(df.b.abs().sort(inplace=False).index)

Out[179]:
   a  b
2  3 -1
3  4  2
0  1 -3
1  2  5
4  5 -9

sort by default is inplace=True so explicitly passing inplace=False will return the series.

Another edit

Thanks to the master @Jeff for this unknown method (to me anyways), you can call order on result of abs which results in cleaner code:

In [31]:
df.reindex(df.b.abs().order().index)

Out[31]:
   a  b
2  3 -1
3  4  2
0  1 -3
1  2  5
4  5 -9

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

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