pandas - 按绝对值排序,而不更改数据 [英] pandas - sort by absolute value without changing the data
问题描述
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屋!