pce*_*con 4 python datetime pandas
给定一个熊猫系列,我正在尝试从日期中减去增量时间。:
date_current = hh.groupby('group').agg({'issue_date' : [np.min, np.max]})
date_current.issue_date.amax.head(5)
group
_101000000000_0.0 2017-01-03
_102000000000_1.0 2017-02-23
_102000000000_2.0 2017-03-20
_102000000000_3.0 2017-10-01
_103000000000_4.0 2017-01-24
Name: amax, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
可以看出,我已经在处理日期时间了。但是,当我尝试执行减法时,出现错误:
import datetime
months = 4
datetime.timedelta(weeks=4*months)
date_before = date_current.values - datetime.timedelta(weeks=4*months)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-5a7f2a09bab6> in <module>()
2 months = 4
3 datetime.timedelta(weeks=4*months)
----> 4 date_before = date_current.values - datetime.timedelta(weeks=4*months)
TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('O')
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
对我来说工作pandas Timedelta:
date_before = date_current.values - pd.Timedelta(weeks=4*months)
print (date_before)
['2016-09-13T00:00:00.000000000' '2016-11-03T00:00:00.000000000'
'2016-11-28T00:00:00.000000000' '2017-06-11T00:00:00.000000000'
'2016-10-04T00:00:00.000000000']
date_before = date_current - pd.Timedelta(weeks=4*months)
print (date_before)
group
_101000000000_0.0 2016-09-13
_102000000000_1.0 2016-11-03
_102000000000_2.0 2016-11-28
_102000000000_3.0 2017-06-11
_103000000000_4.0 2016-10-04
Name: amax, dtype: datetime64[ns]
print (type(date_before.iloc[0]))
<class 'pandas._libs.tslib.Timestamp'>
Run Code Online (Sandbox Code Playgroud)
在我看来,问题是python timedelta没有转换为pandas Timedelta并引发错误。
但是如果需要使用dates,首先转换datetime为datefor pythondate对象:
date_before = date_current.dt.date - datetime.timedelta(weeks=4*months)
print (date_before)
group
_101000000000_0.0 2016-09-13
_102000000000_1.0 2016-11-03
_102000000000_2.0 2016-11-28
_102000000000_3.0 2017-06-11
_103000000000_4.0 2016-10-04
Name: amax, dtype: object
print (type(date_before.iloc[0]))
<class 'datetime.date'>
Run Code Online (Sandbox Code Playgroud)