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

如何在Pandas中基于各列最小值对指定列进行排序?

按列的时间最小值对DataFrame列排序

问题背景

我有如下格式的数据集:

stops   stops name    0            1           2           3
1           A       21:09:00    17:24:00    17:54:00    17:29:00
2           B       21:10:00    17:25:00    17:55:00    17:27:00
3           C                   17:28:00    17:58:00    17:26:00
4           D       21:16:00                18:01:00    17:23:00
5           E       21:17:00    17:32:00    18:02:00    
6           F       21:20:00    17:35:00    18:05:00    17:20:00

之前我实现了基于特定行(比如站点A)对0-3列按时间排序的代码:

def time_to_seconds(time):
    try:
        h,m,s = time.split(':')
        return int(h) * 3600 + int(m) * 60 + int(s)
    except:
        return -1

def time_cmp(l):
    return [ time_to_seconds(time) for time in l ]

df[df.columns[2:]] = df[df.columns[2:]].sort_values(by=[0],axis=1,key=time_cmp)

现在需要改为基于每列的最小值对这些列排序,期望得到如下结果:

stops   stops name    0            1           2           3
1           A       17:29:00    17:24:00    17:54:00    21:09:00
2           B       17:27:00    17:25:00    17:55:00    21:10:00
3           C       17:26:00    17:28:00    17:58:00            
4           D       17:23:00                18:01:00    21:16:00
5           E                   17:32:00    18:02:00    21:17:00
6           F       17:20:00    17:35:00    18:05:00    21:20:00

解决方案

核心思路是:先将每列的时间转换为秒数,计算每列的最小秒值,再根据该值对列进行排序,最后重新排列DataFrame的对应列。

修改后的代码如下:

import pandas as pd

def time_to_seconds(time):
    try:
        h, m, s = time.split(':')
        return int(h) * 3600 + int(m) * 60 + int(s)
    except:
        return float('inf')  # 空值设为无穷大,避免干扰最小值计算

# 提取需要排序的时间列
time_columns = df.columns[2:]

# 计算每列的最小时间对应的秒数
column_min_values = df[time_columns].apply(
    lambda col: col.apply(time_to_seconds).min()
)

# 根据最小秒值对列进行排序,得到新的列顺序
sorted_column_order = column_min_values.sort_values().index

# 重新排列时间列
df[time_columns] = df[sorted_column_order]

代码说明

  1. 调整time_to_seconds函数:将空值返回float('inf')(无穷大),这样计算最小值时会自动忽略空值,保证结果准确。
  2. 计算每列最小时间:通过apply遍历每列,将列内所有时间转换为秒后取最小值。
  3. 排序列顺序:根据每列的最小秒值对列名进行排序,得到从小到大的列顺序。
  4. 重排DataFrame:将原DataFrame的时间列按新顺序重新赋值,完成排序。

内容的提问来源于stack exchange,提问作者M.Ali Zarrinzade

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:54:36