You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:按指定列排序并自动升序排列其余列

Pandas多列排序:指定列优先,其余列自动升序

问题场景

现有如下Pandas DataFrame,需要先按person和buydate列排序,同时让所有其他列自动按升序排列:

import pandas as pd

df = pd.DataFrame({'person': [1, 1, 1, 2, 3, 3],
                   'brand': ['b', 'a', 'a', 'b', 'a', 'b'],
                   'product': ['A1', 'A1', 'A2', 'B1', 'C1', 'C2'],
                   'buydate': ['20220101', '20220101', '20220401', '20220601', '20220630', '20221201'],
                   'type': ['2', '1', '1', '1', '1', '2'],
                   'price': [50, 20, 200, 300, 20, 150],})

期望排序结果:

personbrandproductbuydatetypeprice
01aA120220101120
11bA120220101250
21aA2202204011200
32bB1202206011300
43aC120220630120
53bC2202212012150

尝试仅按person和buydate排序的代码无法得到预期结果(person=1的前两行顺序错误):

df = df.sort_values(['person', 'buydate'])

要求解决方案运行高效,适配大数据集,可接受lambda方法。

高效解决方案

直接将person、buydate作为首要排序键,再加入所有剩余列组成完整排序列表,利用Pandas矢量化排序的高效性完成需求:

# 构建排序列列表:先指定person、buydate,再加入其余所有列
sort_columns = ['person', 'buydate'] + [col for col in df.columns if col not in ['person', 'buydate']]

# 执行排序(ascending=True为默认,可省略)
df_sorted = df.sort_values(sort_columns)

原理说明

  • 当person和buydate的值相同时,会自动按后续列(brand、product、type、price)依次升序排列,正好匹配你需要的结果。
  • 这种方法基于Pandas原生的sort_values矢量化操作,比lambda自定义排序效率高得多,适合处理大规模数据集。

验证结果

运行上述代码后,person=1且buydate为20220101的两行会按brand(a < b)、type(1 < 2)、price(20 < 50)的顺序排列,完全符合预期。


内容的提问来源于stack exchange,提问作者cookiecookie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:37:44