-2

I have a Python dataframe with one column with dates like below:

Date:
2018-10-19
2018-10-20
2018-10-21
(...)
2019-01-31
2019-02-01

Any ideas on how to add an additional column with the number of days in a month, having something like:

Date       DaysinMonth    
2018-10-19 31
2018-10-20 31
2018-10-21 31
(...)

Thanks

DarkSuniuM
  • 2,523
  • 2
  • 26
  • 43
Jo Costa
  • 421
  • 1
  • 6
  • 17

1 Answers1

3

If you have a dataframe df like the following:

df = pd.DataFrame({'dates': dates, 'vals': np.random.randint(10, size=dates.shape)})

        dates  vals
0  2018-01-01     5
1  2018-01-21     8
2  2018-02-10     1
3  2018-03-02     9
4  2018-03-22     0
5  2018-04-11     3
6  2018-05-01     8
7  2018-05-21     2
8  2018-06-10     4
9  2018-06-30     2
10 2018-07-20     7
11 2018-08-09     5
12 2018-08-29     3
13 2018-09-18     7
14 2018-10-08     6
15 2018-10-28     5
16 2018-11-17     3
17 2018-12-07     4
18 2018-12-27     1

Getting the days in the month is as simple as the following:

df['daysinmonth'] = df['dates'].dt.daysinmonth

        dates  vals  daysinmonth
0  2018-01-01     5           31
1  2018-01-21     8           31
2  2018-02-10     1           28
3  2018-03-02     9           31
4  2018-03-22     0           31
5  2018-04-11     3           30
6  2018-05-01     8           31
7  2018-05-21     2           31
8  2018-06-10     4           30
9  2018-06-30     2           30
10 2018-07-20     7           31
11 2018-08-09     5           31
12 2018-08-29     3           31
13 2018-09-18     7           30
14 2018-10-08     6           31
15 2018-10-28     5           31
16 2018-11-17     3           30
17 2018-12-07     4           31
18 2018-12-27     1           31
PMende
  • 5,171
  • 2
  • 19
  • 26