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

如何将Pandas DataFrame中YYYY-MM-DD格式日期转为年积日(0-364)

如何在Pandas中将日期转换为0-364范围的年积日

嘿,这个需求处理起来超简单,用Pandas自带的datetime工具就能搞定,我给你一步步拆解:

第一步:确保日期列是datetime类型

如果你的日期列目前是字符串格式(比如object类型),得先把它转换成Pandas的datetime类型,不然没法用日期相关的属性:

import pandas as pd

# 假设你的日期列叫'date'
df['date'] = pd.to_datetime(df['date'])

要是不确定列类型,跑个df['date'].dtype看看,显示datetime64[ns]就说明没问题了。

第二步:生成0起始的年积日

Pandas的datetime列有个dt.dayofyear属性,它会返回1-366的数值(平年1-365,闰年1-366)。我们只要给它减1,就能得到从0开始计数的年积日:

# 生成0-364(平年)/0-365(闰年)的年积日
df['day_of_year_0based'] = df['date'].dt.dayofyear - 1

第三步:严格限制在0-364范围(可选)

如果你的需求是不管闰年,必须把取值锁在0-364,那可以把闰年的第366天(也就是dayofyear=366,减1后是365)映射到364。这里推荐用矢量化操作,比apply高效得多:

import numpy as np

df['day_of_year_0_364'] = np.minimum(df['date'].dt.dayofyear - 1, 364)

或者用布尔索引也能实现:

df['day_of_year_0_364'] = df['date'].dt.dayofyear - 1
df.loc[df['day_of_year_0_364'] == 365, 'day_of_year_0_364'] = 364

完整示例

来个实际的例子看看效果:

import pandas as pd
import numpy as np

# 创建测试数据,包含平年、闰年的日期
data = {'date': ['2023-12-31', '2020-12-31', '2023-01-01', '2020-02-29']}
df = pd.DataFrame(data)

# 转换日期类型
df['date'] = pd.to_datetime(df['date'])

# 生成两种年积日列
df['day_of_year_0based'] = df['date'].dt.dayofyear - 1
df['day_of_year_0_364'] = np.minimum(df['date'].dt.dayofyear - 1, 364)

print(df)

输出结果:

date  day_of_year_0based  day_of_year_0_364
0 2023-12-31                 364                 364
1 2020-12-31                 365                 364
2 2023-01-01                   0                   0
3 2020-02-29                  59                  59

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:37:32