import numpy as np
import pandas as pd
np.random.seed(46)
df = pd.DataFrame(np.random.rand(5,3), columns=list('abc')) - 0.5
df
a | b | c | |
---|---|---|---|
0 | 0.283832 | 0.134834 | -0.250957 |
1 | 0.258076 | -0.186923 | 0.437237 |
2 | -0.457135 | -0.059133 | 0.412722 |
3 | -0.044996 | 0.007934 | -0.415092 |
4 | -0.073650 | 0.245717 | 0.367081 |
# sort by absolute value
df.iloc[df['a'].abs().argsort()]
a | b | c | |
---|---|---|---|
3 | -0.044996 | 0.007934 | -0.415092 |
4 | -0.073650 | 0.245717 | 0.367081 |
1 | 0.258076 | -0.186923 | 0.437237 |
0 | 0.283832 | 0.134834 | -0.250957 |
2 | -0.457135 | -0.059133 | 0.412722 |
# If necessary, we can reset the index.
df.iloc[df['a'].abs().argsort()].reset_index(drop=True)
a | b | c | |
---|---|---|---|
0 | -0.044996 | 0.007934 | -0.415092 |
1 | -0.073650 | 0.245717 | 0.367081 |
2 | 0.258076 | -0.186923 | 0.437237 |
3 | 0.283832 | 0.134834 | -0.250957 |
4 | -0.457135 | -0.059133 | 0.412722 |
# To sort in descending order, negate df['a'].abs()
df.iloc[(-df['a'].abs()).argsort()]
a | b | c | |
---|---|---|---|
2 | -0.457135 | -0.059133 | 0.412722 |
0 | 0.283832 | 0.134834 | -0.250957 |
1 | 0.258076 | -0.186923 | 0.437237 |
4 | -0.073650 | 0.245717 | 0.367081 |
3 | -0.044996 | 0.007934 | -0.415092 |
# Note
print("It is important to enclose -df['b'].abs() in parentheses since\n"
"otherwise the negative sign is applied after the argsort which\n"
"will give wrong results.")
df.iloc[-df['a'].abs().argsort()]
It is important to enclose -df['b'].abs() in parentheses since otherwise the negative sign is applied after the argsort which will give wrong results.
a | b | c | |
---|---|---|---|
2 | -0.457135 | -0.059133 | 0.412722 |
1 | 0.258076 | -0.186923 | 0.437237 |
4 | -0.073650 | 0.245717 | 0.367081 |
0 | 0.283832 | 0.134834 | -0.250957 |
3 | -0.044996 | 0.007934 | -0.415092 |
# If necessary, index can be reset as before.
df.iloc[(-df['a'].abs()).argsort()].reset_index(drop=True)
a | b | c | |
---|---|---|---|
0 | -0.457135 | -0.059133 | 0.412722 |
1 | 0.283832 | 0.134834 | -0.250957 |
2 | 0.258076 | -0.186923 | 0.437237 |
3 | -0.073650 | 0.245717 | 0.367081 |
4 | -0.044996 | 0.007934 | -0.415092 |