问题描述
本地熊猫Timedelta()
(版本为0.20.3
)无法通过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.
来自 Timedelta文档:
我确实可以按除法转换为另一个timedelta:
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
但是astype()
失败:
day.astype('timedelta64[h]')
# AttributeError: 'Timedelta' object has no attribute 'astype'
文档中的示例实际上并未使用pd.Timedelta()
,这似乎是问题的一部分.取而代之的是,它使用Series(date_range)
减法和datetime.timedelta
(鉴于存在本地的熊猫Timedelta()
,这似乎有点可笑).
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
但是,与我的示例中的day
类型不同:
The type of day
from my example, however, is different:
type(day)
# <class 'pandas._libs.tslib.Timedelta'>
我还没有挖掘出tslib
的源代码,以了解幕后发生的事情-希望有人可以清除文档中发生的事情与我在此处试图做的事情之间的看似差异.谢谢!
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!
推荐答案
pd.Timedelta
没有方法astype
,而pd.TimedeltaIndex
有.
pd.to_timedelta([day]).astype('timedelta64[h]')[0]
24
这篇关于无法使用astype()转换Timedelta对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!