Python numpy: cannot convert datetime64[ns] to datetime64[D] (to use with Numba)

后端 未结 2 1117
面向向阳花
面向向阳花 2020-12-03 01:22

I want to pass a datetime array to a Numba function (which cannot be vectorised and would otherwise be very slow). I understand Numba supports numpy.datetime64. However, it

2条回答
  •  生来不讨喜
    2020-12-03 01:38

    Ran into the same error when calculating number of business days between two dates:

    from pandas.tseries.offsets import MonthBegin
    import numpy as np 
    
    # Calculate the beginning of the month from a given date
    df['Month_Begin'] = pd.to_datetime(df['MyDateColumn'])+ MonthBegin(-1)
    
    # Calculate # of Business Days
    # Convert dates to string to prevent type error [D]
    df['TS_Period_End_Date'] = df['TS_Period_End_Date'].dt.strftime('%Y-%m-%d')
    df['Month_Begin'] = df['Month_Begin'].dt.strftime('%Y-%m-%d')
    
    df['Biz_Days'] = np.busday_count(df['Month_Begin'], df['MyDateColumn']) #<-- Error if not converted into strings.
    

    My workaround was to convert the dates using ".dt.strftime(''%Y-%m-%d')". It worked in my particular case.

提交回复
热议问题