Python 按绝对值排序而不改变数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30486263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting by absolute value without changing the data
提问by afinit
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:
我正在寻找一种简单的方法来按特定列的绝对值对 Pandas 数据框进行排序,但实际上不更改数据框中的值。类似于sorted(df, key=abs)
. 所以如果我有一个像这样的数据框:
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:
对 'b' 排序时得到的排序数据如下所示:
a b
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9
采纳答案by EdChum
回答by cs95
Towards more idiomatic pandas: Use argsort
走向更惯用的熊猫:使用 argsort
A cleaner approach would be to call Series.argsort
on the absolute values, and then index:
更简洁的方法是调用Series.argsort
绝对值,然后索引:
df.iloc[df['b'].abs().argsort()]
a b
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9
If you need to reset the index, use Series.reset_index
,
如果您需要重置索引,请使用Series.reset_index
,
df.iloc[df['b'].abs().argsort()].reset_index(drop=True)
a b
0 3 -1
1 4 2
2 1 -3
3 2 5
4 5 -9
Lastly, since argsort
does not have an ascending
parameter to specify ascending/descending order, you will need to negate df['b'].abs()
to sort by descending order.
最后,由于argsort
没有ascending
用于指定升序/降序的参数,您需要否定df['b'].abs()
以按降序排序。
df.iloc[(-df['b'].abs()).argsort()]
a b
4 5 -9
1 2 5
0 1 -3
3 4 2
2 3 -1
You can do this with NumPy as well—use np.abs
and ndarray.argsort
.
你也可以用 NumPy 来做到这一点——使用np.abs
和ndarray.argsort
。
df.iloc[np.abs(df['b'].values).argsort()]
a b
2 3 -1
3 4 2
0 1 -3
1 2 5
4 5 -9
Or, for descendingorder,
或者,对于降序,
df.iloc[(-np.abs(df['b'].values)).argsort()]
a b
4 5 -9
1 2 5
0 1 -3
3 4 2
2 3 -1