[英]Convert positive values based on a filter condition in a DataFrame to negative values
[英]Sort values of a dataframe column based on positive and negative values?
我的 df 列由 +ve 和 -ve 列組成。
A B
0 a 5
1 b -13
2 c 15
3 d -10
有沒有辦法整理 +ve 值升序和 -ve 值降序
A B
0 a 5
1 c 15
2 d -10
3 b -13
首先使用boolean indexing
過濾,按DataFrame.sort_values
和最后一個concat
排序:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.