9

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!

andrew_reece
  • 20,390
  • 3
  • 33
  • 58

2 Answers2

12

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

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

24
piRSquared
  • 285,575
  • 57
  • 475
  • 624
0
df['timedelta'] = df['timedelta'].apply(pd.to_timedelta)
4b0
  • 21,981
  • 30
  • 95
  • 142
DataYoda
  • 771
  • 5
  • 18
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Vickel Aug 17 '21 at 21:45