簡體   English   中英

在一列中使用交替的正值和負值對 Dataframe 進行排序

[英]Sorting a Dataframe with alternating positive and negative values in one column

請幫助我將 df 排序為 df1,換句話說,我正在嘗試通過 col3 對 df 進行排序,以確保 col3 中的值從正到負交替:

df(原始數據框)

    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 function 作為鍵並得到以下結果,這不是我想要的

`

# 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

一種使用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)

Output(正先):

    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

Output(先負):

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM