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

如何为Pandas DataFrame的年份列添加对应年份天数列?

解决方法

你的错误原因是:pd.to_datetime(df["Year"])会将年份转换为对应年份的1月1日00:00的datetime对象,其dt属性并没有days方法,因此触发AttributeError。

以下是两种可行的实现方式:

方法1:利用年份周期对象判断闰年

通过pd.Period创建年份周期对象,直接判断是否为闰年,对应赋值366或365天:

import pandas as pd

df = pd.DataFrame({"Index":[0, 1, 2, 3, 4, 5],
                   "Year":[2019, 2020, 2021, 2022, 2023, 2024]})

df["Days"] = df["Year"].apply(lambda x: 366 if pd.Period(x, 'Y').is_leap_year else 365)
print(df)

方法2:通过datetime的闰年属性映射

将年份转为datetime后,利用dt.is_leap_year获取布尔值,再映射为对应天数:

import pandas as pd

df = pd.DataFrame({"Index":[0, 1, 2, 3, 4, 5],
                   "Year":[2019, 2020, 2021, 2022, 2023, 2024]})

df["Days"] = pd.to_datetime(df["Year"], format="%Y").dt.is_leap_year.map({True: 366, False: 365})
print(df)

两种方法执行后都会得到你期望的输出:

Index  Year  Days
0      0  2019   365
1      1  2020   366
2      2  2021   365
3      3  2022   365
4      4  2023   365
5      5  2024   366

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:45:45