Sort values of a dataframe column based on positive and negative values?

余生长醉 提交于 2021-02-10 05:11:00

问题


I have df column consisting of +ve and -ve columns.

       A          B
0      a           5
1      b         -13
2      c          15
3      d         -10

And is there a way to sort out +ve values ascending and -ve values descending

       A          B
0      a           5
1      c          15
2      d         -10
3      b         -13

回答1:


First filter both with boolean indexing, sorting by DataFrame.sort_values and last concat together:

mask = df['B'].gt(0)
df = pd.concat([df[mask].sort_values('B'),
                df[~mask].sort_values('B', ascending=False)], ignore_index=True)
print (df)
   A   B
0  a   5
1  c  15
2  d -10
3  b -13


来源:https://stackoverflow.com/questions/58056316/sort-values-of-a-dataframe-column-based-on-positive-and-negative-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!