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
相关产品推荐
相关产品推荐

