2

python newbie here. I am trying to create a df where 1 column is a month 'YYYY-MM' which I have created in a dict below (tips on generating this using code would be appreciated). I am stuck trying to get the weekdays column populated using the month_list.

import pandas as pd
df = pd.DataFrame({'month_list':['2019-01', '2019-02', '2019-03', '2019-04']})
df['weekdays'] = ''

I tried this code, but this only works for correctly for the first row. (i understand why this is, i just don't know the best way to complete each row correctly)

df.weekdays = np.busday_count(month_list[0], month_list[0+1])
df
purlla
  • 23
  • 3

2 Answers2

3

Convert values to datetimes and to strings by Series.dt.strftime, then add one month and pass to np.busday_count:

df = pd.DataFrame({'month_list':['2019-01', '2019-02', '2019-03', '2019-04']})

month_list = pd.to_datetime(df['month_list'])
a = month_list.dt.strftime('%Y-%m-%d')
b = (month_list + pd.offsets.DateOffset(months=1)).dt.strftime('%Y-%m-%d')

df['weekdays'] = np.busday_count(a, b)

print (df)
  month_list  weekdays
0    2019-01        23
1    2019-02        20
2    2019-03        21
3    2019-04        22

Only numpy solution:

month_list = pd.to_datetime(df['month_list'])

a = month_list.to_numpy().astype('datetime64[M]')
b = a + np.array([1], dtype='timedelta64[M]') 

df['weekdays'] = np.busday_count(a, b)
print (df)
  month_list  weekdays
0    2019-01        23
1    2019-02        20
2    2019-03        21
3    2019-04        22
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2
from pandas.tseries.offsets import MonthEnd
df = pd.DataFrame({'month_list': pd.date_range('2019-01', '2019-12', freq='MS')})

df['weekdays'] = np.busday_count(df.month_list.values.astype('datetime64[D]'), (df.month_list + MonthEnd(0)).values.astype('datetime64[D]')) + 1

Result:

   month_list  weekdays
0  2019-01-01        23
1  2019-02-01        20
2  2019-03-01        22
3  2019-04-01        22
4  2019-05-01        23
5  2019-06-01        21
6  2019-07-01        23
7  2019-08-01        23
8  2019-09-01        21
9  2019-10-01        23
10 2019-11-01        22
11 2019-12-01        22
Stef
  • 28,728
  • 2
  • 24
  • 52