简体   繁体   English

如何排列 Pandas dataframe 基于所有行值为正,一行值为负,两行值为负...和所有行值为负,

[英]How to arrange Pandas dataframe based on all row values positive, one row values negative, two row values negative ... and all row values negative,

How to arrange Pandas dataframe based on all row values positive, one row values negative, two row values negative... and all row values negative,如何排列 Pandas dataframe 基于所有行值为正,一行值为负,两行值为负...和所有行值为负,

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预计 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).它获取大于 0 的行,将它们跨列求和,然后根据值,按降序排序(所有正数应该是最高的,其次是一个负数,两个负数,并且都是负数)。 After the sorting, the num column can be dropped, as it has served its purpose.排序后,可以删除num列,因为它已达到目的。

(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM