I have an array of values that can be any type. When they are time-deltas, it causes a problem:
>>> d = np.diff(np.array([
... '2022-10-13 10:00:00', '2022-10-13 10:30:00',
... '2022-10-13 11:00:00', '2022-10-14 10:00:00',
... '2022-10-13 23:00:00', '2022-10-14 00:00:00'
... ], dtype='datetime64[ns]'))
>>> d
array([ 1800000000000, 1800000000000, 82800000000000, -39600000000000,
3600000000000], dtype='timedelta64[ns]')
I want get a mask for the elements that are less than zero:
>>> d < 0
UFuncTypeError: Cannot cast ufunc 'less' input 0 from dtype('<m8[ns]') to dtype('<m8') with casting rule 'same_kind'
Since I want a general purpose solution that works for any dtype, I tried using d[0]
as a template, also without luck:
>>> d < d.dtype(0)
TypeError: 'numpy.dtype[timedelta64]' object is not callable
The only way I've found to bypass this by constructing a special zero:
>>> if d.dtype.type == np.timedelta64: print(d < np.timedelta64(0, 'ns'))
[False False False True False]
Is there a general purpose approach that will let me check when an array is negative that will work with time-deltas?
CodePudding user response:
I think you can use np.sign
.
np.sign(d)
Output:
array([ 1, 1, 1, -1, 1], dtype='timedelta64[ns]')
CodePudding user response:
I realized that I almost had it:
>>> d < d.dtype.type(0)
array([False, False, False, True, False])