【问题标题】:calendar.monthrange() - ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()calendar.monthrange() - ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】: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

标签: python pandas


【解决方案1】:

使用 DatetimeIndex 的days_in_month 属性:

df = pd.DataFrame({'date':pd.date_range('01/01/2019', periods=12, freq='MS')})
df['No of Days in this Month'] = df['date'].dt.days_in_month
df

输出:

         date  No of Days in this Month
0  2019-01-01                        31
1  2019-02-01                        28
2  2019-03-01                        31
3  2019-04-01                        30
4  2019-05-01                        31
5  2019-06-01                        30
6  2019-07-01                        31
7  2019-08-01                        31
8  2019-09-01                        30
9  2019-10-01                        31
10 2019-11-01                        30
11 2019-12-01                        31

【讨论】:

    【解决方案2】:

    可以是这样的:

    # dt is referred to datetime
    df['NumDays'] = df['Date_Field'].dt.days_in_month
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2019-01-24
      • 1970-01-01
      • 2021-03-21
      • 2021-05-27
      • 2021-04-07
      • 2022-12-29
      • 2018-07-09
      • 2020-02-12
      相关资源
      最近更新 更多