无法使用 astype() 转换 Timedelta 对象
Timedelta object cannot be converted with astype()
原生 Pandas Timedelta()
(版本 0.20.3
),无法使用 astype()
转换为特定频率,尽管文档说这应该是可能的.我想弄清楚我错过了什么。
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.
我确实可以用另一个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
(这似乎有点有趣,因为有一个本地 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
的类型不同:
type(day)
# <class 'pandas._libs.tslib.Timedelta'>
我还没有深入研究 tslib
源代码来弄清楚幕后发生了什么——希望有人能澄清文档中发生的事情和我正在尝试的事情之间看似不一致的地方在这里做。谢谢!
pd.Timedelta
没有方法 astype
而 pd.TimedeltaIndex
有。
pd.to_timedelta([day]).astype('timedelta64[h]')[0]
24
df['timedelta'] = df['timedelta'].apply(pd.to_timedelta)
原生 Pandas Timedelta()
(版本 0.20.3
),无法使用 astype()
转换为特定频率,尽管文档说这应该是可能的.我想弄清楚我错过了什么。
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.
我确实可以用另一个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
(这似乎有点有趣,因为有一个本地 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
的类型不同:
type(day)
# <class 'pandas._libs.tslib.Timedelta'>
我还没有深入研究 tslib
源代码来弄清楚幕后发生了什么——希望有人能澄清文档中发生的事情和我正在尝试的事情之间看似不一致的地方在这里做。谢谢!
pd.Timedelta
没有方法 astype
而 pd.TimedeltaIndex
有。
pd.to_timedelta([day]).astype('timedelta64[h]')[0]
24
df['timedelta'] = df['timedelta'].apply(pd.to_timedelta)