如何在Pandas中根据列值实现单列的不同排序规则?
解决方案
需求梳理
你需要实现的排序逻辑是:
- 先对整个DataFrame按
dfindex升序排序; - 将排序后连续的同action行划分为组;
- 组内排序规则:
'buy'组按price降序,'sell'组按price升序。
可行代码实现
import pandas as pd # 构造测试数据(可替换为你的原始DataFrame) data = { 'dfindex': [4,7,2,3,6,5,1,8], 'price': [0.9,0.7,0.9,0.4,0.6,0.8,0.7,0.9], 'action': ["'sell'","'buy'","'buy'","'sell'","'sell'","'buy'","'buy'","'buy'"] } tx_hist = pd.DataFrame(data) # 步骤1:按dfindex升序排序 tx_hist = tx_hist.sort_values('dfindex', ascending=True).reset_index(drop=True) # 步骤2:标记连续同action的组 tx_hist['group_id'] = (tx_hist['action'] != tx_hist['action'].shift()).cumsum() # 步骤3:分组应用自定义排序 def sort_group(group): if group['action'].iloc[0] == "'buy'": return group.sort_values('price', ascending=False) else: return group.sort_values('price', ascending=True) # 执行分组排序并清理辅助列 result = tx_hist.groupby('group_id', group_keys=False).apply(sort_group).drop('group_id', axis=1) print(result)
运行后输出结果完全匹配你的预期:
dfindex price action 0 2 0.9 'buy' 1 1 0.7 'buy' 2 3 0.4 'sell' 3 4 0.9 'sell' 4 5 0.8 'buy' 5 6 0.6 'sell' 6 8 0.9 'buy' 7 7 0.7 'buy'
现有代码问题分析
初始
sort_values代码:
仅按dfindex升序+price统一降序排序,未区分action的不同排序规则,不符合需求。自定义
sorttxhist函数:list.sort()是原地排序,返回None,赋值给buytxs/selltx会导致后续赋值错误;- 循环未处理
w超出DataFrame长度的边界情况,容易报错; - 直接修改
iloc会触发SettingWithCopyWarning,且逻辑未正确识别连续分组。
内容的提问来源于stack exchange,提问作者TheRealOrange
相关产品推荐
相关产品推荐

