2017-05-23 211 views
2

我想減去日期增量時間,給予大熊貓系列:從日期減去timedelta - 大熊貓

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] 

可以看出,I'n已經與日期時間的工作。但是,當我嘗試執行減法時,出現錯誤:

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

我錯過了什麼?

回答

2

對我的作品pandasTimedelta

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

在我看來問題是pythontimedelta不會轉換爲pandasTimedelta並引發錯誤。

但是,如果需要與date s工作,先轉換datetimedate爲蟒蛇date對象:

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

謝謝。我雖然可以使用datetime中的timedelta函數。 – pceccon

+1

我想如果使用'熊貓',最好是使用熊貓功能,因爲熊貓開發者主要實施它們。這似乎是錯誤,可以創建新的[問題](https://github.com/pandas-dev/pandas/issues) – jezrael

1

由於jezrael pointed out,有熊貓的方式,但你也可以使用.dt accessor做到這一點爲datetime :

df.dt.values - dt.timedelta(weeks=4 * months) 

測試代碼:

import datetime as dt 
import pandas as pd 

df = pd.Series([dt.datetime.now()]) 
print(df) 

months = 4 
print(df.values - pd.Timedelta(weeks=4*months)) 
print(df.dt.values - dt.timedelta(weeks=4 * months)) 

結果:

0 2017-05-23 05:36:53.300 
dtype: datetime64[ns] 

['2017-01-31T05:36:53.300000000'] 

DatetimeIndex(['2017-01-31 05:36:53.300000'], dtype='datetime64[ns]', freq=None)