1

I have a pandas dataframe that has a date field. I'm trying to use this field to calculate the number of days in the month of that date. However, when I use the code below, I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or 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]

I've tested to see if the .year and .month are working by creating two separate columns in the DF with that data.

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]

The resulting 'year' column had the correct year, and the 'month' column had the correct month, but when I tried to use them in monthrange() I get the same ValueError.

Any guidance would be appreciated.

Thanks.

caddie
  • 169
  • 1
  • 3
  • 11
  • this may [help](https://docs.python.org/3/library/exceptions.html#ValueError) – sahasrara62 Feb 11 '20 at 21:08
  • Caddie, do you just want the day of month? Ie Feb 2, 1998 returns 2 and March 17,2010 returns 17? `df['date'].dt.day` will work. Look at using the [`.dt`](https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#basics-dt-accessors) accessor for pandas. – Scott Boston Feb 11 '20 at 21:18
  • Hey Scott, thanks for your reply. What I'm looking for is the number of days in that specific month. So, if the date is 01/26/2020, I'd expect to see 31. – caddie Feb 11 '20 at 21:20
  • 1
    Ah.. @caddie there is an attribute [days_in_month](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.days_in_month.html?highlight=days_in_month#pandas.Series.dt.days_in_month) Use, `df['date'].dt.days_in_month`. – Scott Boston Feb 11 '20 at 21:21
  • https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o – AMC Feb 11 '20 at 21:45

2 Answers2

2

Use days_in_month attribute of DatetimeIndex:

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

Output:

         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
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

Can be something like this:

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