如何将DataFrame按col3列实现正负交替排序?
解决Pandas DataFrame按列正负交替排序的问题
需求说明
需要将原始DataFrame按col3列排序,使col3的值呈现正负交替的状态,且绝对值从小到大排列(相同绝对值的正数在前,负数在后,多出来的同符号值依次放在对应位置)。
原始DataFrame(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(df1):
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的绝对值排序,只能实现绝对值从小到大排列,但无法保证正负交替的顺序,导致负数会连续出现(如排序结果中-38后接38,不符合正负交替要求)。
解决方案代码
import pandas as pd from itertools import zip_longest # 创建原始DataFrame 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] }) # 拆分正数和负数DataFrame,均按绝对值升序排序 pos_df = df[df['col3'] > 0].sort_values(by='col3', key=lambda x: abs(x)).reset_index(drop=True) neg_df = df[df['col3'] < 0].sort_values(by='col3', key=lambda x: abs(x)).reset_index(drop=True) # 交替拼接正负行,处理数量不等的情况 rows = [] for pos_row, neg_row in zip_longest(pos_df.itertuples(index=False), neg_df.itertuples(index=False)): if pos_row is not None: rows.append(pos_row) if neg_row is not None: rows.append(neg_row) # 转换为目标DataFrame df1 = pd.DataFrame(rows, columns=df.columns) print(df1)
代码说明
- 拆分正负数据:将原始DataFrame分为正数集和负数集,分别按
col3的绝对值升序排序,保证相同绝对值的数值能对应上。 - 交替拼接:使用
zip_longest函数依次取排序后的正数行和负数行,实现正负交替;若某一类数据(正/负)数量更多,剩余行直接追加到末尾,符合期望结果的排列逻辑。
内容的提问来源于stack exchange,提问作者NickM
相关产品推荐
相关产品推荐

