2017-05-23 4 views
2

私はI'nはすでに日付時刻と協力して、見ることができるようにパンダシリーズ:引くとは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] 

を与え、日付からデルタ時間を減算しようとしています。しかし、減算を実行しようとすると、エラーが発生します。

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

pythontimedeltapandasTimedeltaに変換し、それはエラーが発生していないです。 date Sでの作業が必要で、最初のpython dateオブジェクトに対してdatedatetimeを変換する場合

しかし

は:

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

私は 'pandas'を使うと、パンダの開発者が主にそれらを実装するので、パンダの機能を使う方が良いと思います。ここにバグがあるようですが、新しい[issue](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) 
関連する問題