如何使用NumPy为日期数组添加对应整数月份?
解决方案
方法一:使用Pandas(推荐,代码简洁易维护)
Pandas对日期时间的加减操作支持更完善,能直接处理月份的偏移:
import pandas as pd import numpy as np date = np.array(['2023-01-01', '2023-02-02', '2023-03-03']) months = np.array([3, 2, 1]) # 将日期数组转为Pandas日期序列 date_series = pd.to_datetime(date) # 逐个添加对应月份数 expectation = date_series + pd.to_timedelta(months, unit='M') # 转回Numpy数组(若需要字符串格式可追加.astype(str)) expectation = expectation.to_numpy() # 输出结果:array(['2023-04-01T00:00:00.000000000', '2023-04-02T00:00:00.000000000', '2023-04-03T00:00:00.000000000'], dtype='datetime64[ns]')
方法二:纯Numpy实现(无需额外依赖)
如果不想引入Pandas,可以手动拆分年、月、日分量计算:
import numpy as np date = np.array(['2023-01-01', '2023-02-02', '2023-03-03'], dtype='datetime64[D]') months = np.array([3, 2, 1]) # 提取原始日期的年、月、日分量 years = date.astype('datetime64[Y]').astype(int) + 1970 # datetime64[Y]从1970年开始计数 months_original = date.astype('datetime64[M]').astype(int) % 12 + 1 # 转换为1-12的月份 days = date.astype('datetime64[D]').astype(int) - date.astype('datetime64[M]').astype('datetime64[D]').astype(int) + 1 # 提取当月第几天 # 计算新的年、月 new_months_total = months_original + months new_years = years + (new_months_total - 1) // 12 new_months = (new_months_total - 1) % 12 + 1 # 构造新日期数组 expectation = np.array([f"{y}-{m:02d}-{d:02d}" for y, m, d in zip(new_years, new_months, days)], dtype='datetime64[D]') # 输出结果:array(['2023-04-01', '2023-04-02', '2023-04-03'], dtype='datetime64[D]')
说明:Numpy原生的
timedelta64不支持直接进行月份偏移(因为不同月份天数不同),所以需要手动处理年、月的进位逻辑。
内容的提问来源于stack exchange,提问作者Michael An
相关产品推荐
相关产品推荐

