pandas 在一列中交替使用正值和负值对 Dataframe 进行排序

jgwigjjp  于 2022-12-10  发布在  其他
关注(0)|答案(1)|浏览(144)

请帮助我将df排序到df1中,换句话说,我正在尝试按col3对df进行排序,以确保col3中的值从正变为负:
df(原始 Dataframe )

col1    col2    col3
0   1   -1  -38
1   2   -2  45
2   3   -3  79
3   4   -4  -55
4   5   -5  31
5   6   -6  38
6   7   -7  -45
7   8   -8  -79
8   9   -9  55
9   10  -10 -31
10  11  -11 55
11  12  -12 -55

期望 Dataframe

col1    col2    col3
0   5   -5  31
1   10  -10 -31
2   6   -6  38
3   1   -1  -38
4   2   -2  45
5   7   -7  -45
6   9   -9  55
7   4   -4  -55
8   11  -11 55
9   12  -12 -55
10  3   -3  79
11  8   -8  -79

我尝试按col3排序并使用lambda函数作为键,得到了下面的结果,这不是我想要的
`

# first, we need to import the Pandas library
import pandas as pd

# create a sample DataFrame with three columns
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5,6,7,8,9,10,11,12], 'col2': [-1, -2, -3, -4, -5,-6,-7,-8,-9,-10,-11,-12], \
                   'col3': [-38,45,79,-55,31,38,-45,-79,55,-31,55,-55]})

# sort the 'col3' column in ascending order by the absolute value of each element
df = df.sort_values(by='col3', key=lambda x: abs(x))

`

col1    col2    col3
4   5   -5  31
9   10  -10 -31
0   1   -1  -38
5   6   -6  38
1   2   -2  45
6   7   -7  -45
3   4   -4  -55
8   9   -9  55
10  11  -11 55
11  12  -12 -55
2   3   -3  79
7   8   -8  -79
fkvaft9z

fkvaft9z1#

一种方法是先使用pandas.DataFrame.groupby,然后使用sort_values和多个列:

keys = ["abs", "order", "sign"]

s = df["col3"]

df["abs"] = s.abs()
df["order"] = df.groupby(["abs", "col3"]).cumcount()

# If you want positive to come first
df["sign"] = s.lt(0)

# If you want negative to come first
# df["sign"] = s.gt(0)

new_df = df.sort_values(keys).drop(keys, axis=1)
print(new_df)

输出(正极优先):

col1  col2  col3
4      5    -5    31
9     10   -10   -31
5      6    -6    38
0      1    -1   -38
1      2    -2    45
6      7    -7   -45
8      9    -9    55
3      4    -4   -55
10    11   -11    55
11    12   -12   -55
2      3    -3    79
7      8    -8   -79

输出(负向优先):

col1  col2  col3
9     10   -10   -31
4      5    -5    31
0      1    -1   -38
5      6    -6    38
6      7    -7   -45
1      2    -2    45
3      4    -4   -55
8      9    -9    55
11    12   -12   -55
10    11   -11    55
7      8    -8   -79
2      3    -3    79

相关问题