Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timedelta object cannot be converted with astype()

A native Pandas Timedelta() (with version 0.20.3), can't convert to a specific frequency with astype(), although the docs say it should be possible. I'm trying to figure out what I'm missing.

From the Timedelta docs:

Timedelta Series, TimedeltaIndex, and Timedelta scalars can be converted to other ‘frequencies’ by dividing by another timedelta, or by astyping to a specific timedelta type.

It's true that I can convert by division with another timedelta:

import pandas as pd
pd.__version__ 
# 0.20.3

day = pd.Timedelta("1 day")
day / pd.Timedelta(1, "h") 
# 24.0

But astype() fails:

day.astype('timedelta64[h]')
# AttributeError: 'Timedelta' object has no attribute 'astype'

The example in the documentation doesn't actually use pd.Timedelta(), and that seems to be part of the issue. Instead, it uses Series(date_range) subtraction and datetime.timedelta (which seems a little funny given there's a native Pandas Timedelta()).

# This example is used in the Timedelta docs.
import datetime
td = pd.Series(pd.date_range('20130101', periods=4)) - pd.Series(pd.date_range('20121201', periods=4))
td[2] += datetime.timedelta(minutes=5, seconds=3)
td[3] = np.nan

td
0   31 days 00:00:00
1   31 days 00:00:00
2   31 days 00:05:03
3                NaT
dtype: timedelta64[ns]
# ...
td.astype('timedelta64[s]')
Out[75]: 
0    2678400.0
1    2678400.0
2    2678703.0
3          NaN
dtype: float64

The type of day from my example, however, is different:

type(day)
# <class 'pandas._libs.tslib.Timedelta'>

I haven't yet dug into the tslib source to figure out what's going on under the hood - hoping someone can clear up the seeming discrepancy between what's going on in the docs and what I'm trying to do here. Thanks!

like image 904
andrew_reece Avatar asked Aug 27 '17 04:08

andrew_reece


1 Answers

pd.Timedelta doesn't have a the method astype while pd.TimedeltaIndex does.

pd.to_timedelta([day]).astype('timedelta64[h]')[0]

24
like image 197
piRSquared Avatar answered Nov 15 '22 23:11

piRSquared