orange
orange

Reputation: 8090

Check if series is timedelta

I'd like to transform a Pandas series in case its dtype is np.timedelta64. Is there any way I can check the type of the series? series.dtype == np.timedelta64 does not work. I could check the first element (isinstance(first_element, np.timedelta64)) or use the series.dtype.name, but thought there must be a better way to achieve this.

Upvotes: 5

Views: 2130

Answers (1)

Jeff
Jeff

Reputation: 129038

In [3]: s = Series(pd.to_timedelta(np.arange(5),unit='s'))

In [4]: s
Out[4]:
0   00:00:00
1   00:00:01
2   00:00:02
3   00:00:03
4   00:00:04
dtype: timedelta64[ns]

In [6]: s.dtype == 'timedelta64[ns]'
Out[6]: True

In [10]: s.dtype == 'm8[ns]'
Out[10]: True

# select_dtypes is only defined on frames
# this is generally the most robust method
In [11]: s.to_frame().select_dtypes(include=['timedelta'])
Out[11]:
         0
0 00:00:00
1 00:00:01
2 00:00:02
3 00:00:03
4 00:00:04

In [12]: from pandas.core.common import is_timedelta64_dtype

In [13]: is_timedelta64_dtype(s.dtype)
Out[13]: True

Upvotes: 5

Related Questions