How to arrange Pandas dataframe based on all row values positive, one row values negative, two row values negative... and all row values negative,
df=pd.DataFrame({
'x':[1, 2, 3, -1, -2, -3],
'y':[-1, 3, 2, -4, 3, -2],
'z':[1 , 1, 5, 2, 1, -1]}]
expected output
index x y z
1 2 3 1 all positive
2 3 2 5
4 -2 3 1 one negative
0 1 -1 1
3 -1 -4 2 two negative
5 -3 -2 -1 all negative
Try this:
It gets the rows that are greater than 0, sums them across the columns, then based on the values, sort in descending order (all positive should be the highest, followed by one negative, two negative, and all negative). After the sorting, the num
column can be dropped, as it has served its purpose.
(df.assign(num=df.ge(0).sum(1))
.sort_values("num", ascending=False)
.drop(columns=["num"])
)
x y z
1 2 3 1
2 3 2 5
4 -2 3 1
0 1 -1 1
3 -1 -4 2
5 -3 -2 -1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.