5

I want to calculate the business days between two columns type pandas.core.series.Series

between Received date and complete date #business days only
I was trying to use np.busday_count(Received date,complete date,weekmask= "Fri Sat") but I was getting :

TypeError: Iterator operand 0 dtype could not be cast from dtype('M8[us]') to dtype('M8[D]') according to the rule 'safe'

Here is part of my dataframe:

     Received   Complete
0  2018-09-10 2018-09-25
1  2018-07-16 2018-08-13
2  2018-07-05 2018-07-11
3  2018-07-05 2018-07-23
4  2018-07-26 2018-08-14
5  2018-07-04 2018-08-28
6  2018-07-05 2018-07-10
7  2018-07-05 2018-07-10
8  2018-07-05 2018-07-22
9  2018-07-05 2018-07-22
10 2018-07-05 2018-07-19
jpp
  • 159,742
  • 34
  • 281
  • 339
Khaled Khanfar
  • 105
  • 1
  • 6

1 Answers1

7

As indicated in the error, convert to 'datetime64[D]' before using np.busday_count:

res = np.busday_count(df['Received'].values.astype('datetime64[D]'),
                      df['Complete'].values.astype('datetime64[D]'),
                      weekmask= "Fri Sat")

# array([ 4,  8,  2,  6,  6, 16,  2,  2,  6,  6,  4], dtype=int64)
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thanks it make sense but I'm working on xlsx sheet sorry I didn't mention this in the beginning – Khaled Khanfar Jan 17 '19 at 17:47
  • @KhaledKhanfar, CSV is not relevant to my answer (and I've removed it). You just need to make sure `df['Receved']` and `df['Complete']` are `datetime` series. – jpp Jan 17 '19 at 17:51
  • Thanks a lot for following up on this and the type is datetime but I'm getting : Error parsing datetime string " 9-4-2018" at position 3 and I've looked into this specific value type and it was datetime :( – Khaled Khanfar Jan 17 '19 at 18:03
  • @KhaledKhanfar, Looks like your series is not really `datetime` then. Check `df.dtypes` to confirm. There are *many* questions on SO on how to convert different string formats to `datetime`. It's beyond the scope of this question. – jpp Jan 17 '19 at 18:04
  • ,Thanks a lot for you help I will look into it :) – Khaled Khanfar Jan 17 '19 at 18:15