我试着从日期中减去delta时间,给一个熊猫系列

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]

可以看出,我已经在和约会时间打交道了。但是,当我尝试执行减法时,会得到一个错误:
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')

我错过了什么?

最佳答案

对我来说工作

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'>

在我看来,问题是pandaspython没有转换成timedeltapandas,这会引起错误。
但如果需要使用Timedeltas,首先将pythondate对象的datetime转换为Timedelta
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'>

关于python - 从日期减去timedelta- Pandas ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44134785/

10-09 02:59