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

DataFrame datetime64列调用Period报错ValueError,寻求解决方法

解决方法

你的报错原因是p.Period()仅支持单个日期/时间值,而你传入的是整个time列(Series对象),无法批量处理。下面是两种可行的解决方案:

方法一:直接使用dt访问器(推荐)

利用pandas为datetime类型Series提供的dt访问器,直接调用内置的days_in_month属性:

dt['NB_DAYS'] = dt['time'].dt.days_in_month

方法二:转为Period类型后处理

先通过dt.to_period('M')将datetime列批量转为月份周期的Period对象,再获取当月天数:

dt['NB_DAYS'] = dt['time'].dt.to_period('M').dt.days_in_month

这两种方法都能批量处理整个DataFrame列,无需循环操作单个元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:01:20