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

Pandas多列升序排序但日期时间列降序排序的简便方法

解决方案

方法1:提前定义升序列表,用列表乘法简化参数

假设你已经明确知道需要升序的50列,将它们存入一个列表:

# 替换为你的实际列名列表
ascending_cols = ["col1", "col2", "col3", ..., "col50"]
# 构造排序参数
sort_by = ascending_cols + ["date_time"]
sort_ascending = [True] * len(ascending_cols) + [False]
# 执行排序
sorted_df = df.sort_values(by=sort_by, ascending=sort_ascending)

方法2:自动筛选升序列(如果升序列是除date_time外的指定范围)

如果升序列是除date_time和少数其他列之外的所有列,可以通过列名筛选自动生成列表:

# 定义不需要升序的列(包含date_time)
exclude_cols = ["date_time", "other_col1", "other_col2"]
# 自动生成升序列表
ascending_cols = [col for col in df.columns if col not in exclude_cols]
# 构造排序参数
sort_by = ascending_cols + ["date_time"]
sort_ascending = [True] * len(ascending_cols) + [False]
# 执行排序
sorted_df = df.sort_values(by=sort_by, ascending=sort_ascending)

以上两种方式都能避免手动输入大量True,只需维护列名列表或排除列表,代码更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:54:19