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

如何按日、月、年对Numpy数组中的日期进行排序?

按日、月、年排序Numpy日期字符串数组

你的问题出在直接对字符串数组排序时,是按字典序比较的,只会优先匹配字符串的前几位(也就是日部分),无法识别日期的结构。要实现按日→月→年的优先级排序,可以用以下两种方法:

方法一:使用Numpy的lexsort拆分日期字段排序

先将每个日期字符串拆分为日、月、年的数值数组,再用lexsort按指定优先级排序:

import numpy as np

all_periods = np.array(['01/01/2021', '01/01/2022', '02/01/2021', '02/01/2022',
       '03/01/2020', '03/01/2021', '03/01/2022', '04/01/2020',
       '04/01/2021', '04/01/2022', '05/01/2020', '05/01/2021',
       '06/01/2020', '06/01/2021', '07/01/2020', '07/01/2021',
       '08/01/2020', '08/01/2021', '09/01/2020', '09/01/2021',
       '10/01/2020', '10/01/2021', '11/01/2020', '11/01/2021',
       '12/01/2020', '12/01/2021'], dtype=object)

# 拆分日期为日、月、年的字符串数组
split_dates = np.char.split(all_periods, sep='/').tolist()
# 转换为数值数组,分别提取日、月、年
days = np.array([int(x[0]) for x in split_dates])
months = np.array([int(x[1]) for x in split_dates])
years = np.array([int(x[2]) for x in split_dates])

# 使用lexsort,优先级:日 > 月 > 年(lexsort从右到左读取键)
sorted_indices = np.lexsort((years, months, days))
sorted_periods = all_periods[sorted_indices]

print(sorted_periods)

输出结果会按日升序排列,日相同则按月升序,月相同则按年升序:

array(['01/01/2021', '01/01/2022', '02/01/2021', '02/01/2022',
       '03/01/2020', '03/01/2021', '03/01/2022', '04/01/2020',
       '04/01/2021', '04/01/2022', '05/01/2020', '05/01/2021',
       '06/01/2020', '06/01/2021', '07/01/2020', '07/01/2021',
       '08/01/2020', '08/01/2021', '09/01/2020', '09/01/2021',
       '10/01/2020', '10/01/2021', '11/01/2020', '11/01/2021',
       '12/01/2020', '12/01/2021'], dtype=object)

(注:你的原数组其实已经是按日→月→年的顺序排列的,所以排序后结果和原数组一致;如果原数组混乱,这个方法会正确排序)

方法二:使用Pandas按多字段排序

如果习惯用Pandas,可以将数组转为Series,提取日、月、年作为排序键:

import pandas as pd
import numpy as np

all_periods = np.array(['01/01/2021', '01/01/2022', '02/01/2021', '02/01/2022',
       '03/01/2020', '03/01/2021', '03/01/2022', '04/01/2020',
       '04/01/2021', '04/01/2022', '05/01/2020', '05/01/2021',
       '06/01/2020', '06/01/2021', '07/01/2020', '07/01/2021',
       '08/01/2020', '08/01/2021', '09/01/2020', '09/01/2021',
       '10/01/2020', '10/01/2021', '11/01/2020', '11/01/2021',
       '12/01/2020', '12/01/2021'], dtype=object)

# 转为Series并解析日期
df = pd.DataFrame({'date': all_periods})
df['day'] = pd.to_datetime(df['date'], format='%d/%m/%Y').dt.day
df['month'] = pd.to_datetime(df['date'], format='%d/%m/%Y').dt.month
df['year'] = pd.to_datetime(df['date'], format='%d/%m/%Y').dt.year

# 按day→month→year排序
sorted_df = df.sort_values(by=['day', 'month', 'year'])
sorted_periods = sorted_df['date'].to_numpy()

print(sorted_periods)

这个方法更直观,通过明确指定排序字段的优先级来实现需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:18:24