【发布时间】:2020-05-27 08:41:12
【问题描述】:
我有一个带有日期字段的 pandas 数据框。我正在尝试使用此字段来计算该日期当月的天数。但是,当我使用下面的代码时,出现以下错误:
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
from calendar import monthrange
df['NumDays'] = monthrange(df['Date_Field'].map(lambda x: x.year),df['Date_Field'].map(lambda x: x.month))[1]
我已经通过在 DF 中使用该数据创建两个单独的列来测试 .year 和 .month 是否正常工作。
df['year'] = df['Date_Field'].map(lambda x: x.year)
df['month'] = df['Date_Field'].map(lambda x: x.month)
df['NumDays'] = monthrange(df['year'], df['month'])[1]
生成的“年”列具有正确的年份,“月”列具有正确的月份,但是当我尝试在 monthrange() 中使用它们时,我得到相同的 ValueError。
任何指导将不胜感激。
谢谢。
【问题讨论】:
-
这可能是help
-
Caddie,你只想要月份的哪一天吗?即 1998 年 2 月 2 日返回 2,2010 年 3 月 17 日返回 17?
df['date'].dt.day将起作用。看看对 pandas 使用.dt访问器。 -
嗨,斯科特,感谢您的回复。我正在寻找的是该特定月份的天数。所以,如果日期是 2020 年 1 月 26 日,我希望看到 31 日。
-
啊..@caddie有个属性days_in_month用,
df['date'].dt.days_in_month。