熊猫to_timedelta不相干值返回

问题描述 投票:0回答:1

我正在尝试做一些非常简单的事情,我在数据集上有一个DatetimeIndex,我只想根据最近的输入来保留最近的12个月。

我的数据:AU,按月包含一个条目,并且日期始终是该月的第一天。

现在,当我这样做时:

mask = au.index >= max(au.index) - pd.to_timedelta(12, unit = 'M')
pd.unique(au[mask].index)

Out[5]: 
array(['2018-11-01T00:00:00.000000000', '2018-12-01T00:00:00.000000000',
       '2019-11-01T00:00:00.000000000', '2019-10-01T00:00:00.000000000',
       '2019-09-01T00:00:00.000000000', '2019-08-01T00:00:00.000000000',
       '2019-07-01T00:00:00.000000000', '2019-06-01T00:00:00.000000000',
       '2019-01-01T00:00:00.000000000', '2019-05-01T00:00:00.000000000',
       '2019-04-01T00:00:00.000000000', '2019-03-01T00:00:00.000000000',
       '2019-02-01T00:00:00.000000000'], dtype='datetime64[ns]')

我得到最近的一个月和过去的十二个月,所以总共是13个月。很好,我认为计算中是否包含上个月只是一个问题。

所以我将代码更改为:

mask = au.index >= max(au.index) - pd.to_timedelta(11, unit = 'M')
pd.unique(au[mask].index)

Out[9]: 
array(['2019-11-01T00:00:00.000000000', '2019-10-01T00:00:00.000000000',
       '2019-09-01T00:00:00.000000000', '2019-08-01T00:00:00.000000000',
       '2019-07-01T00:00:00.000000000', '2019-06-01T00:00:00.000000000',
       '2019-01-01T00:00:00.000000000', '2019-05-01T00:00:00.000000000',
       '2019-04-01T00:00:00.000000000', '2019-03-01T00:00:00.000000000',
       '2019-02-01T00:00:00.000000000'], dtype='datetime64[ns]')

现在我只回来了11个月,而不是预期的12个月。

有人知道为什么吗?

谢谢

PS:我知道可能会有一种使用relativedelta做到这一点的方法。但是我很好奇了解熊猫的行为。

python pandas timedelta
1个回答
0
投票

谢谢@Quang Huong,使用它解决了我的问题:

mask = au.index >= max(au.index) + pd.DateOffset(months=-2)
© www.soinside.com 2019 - 2024. All rights reserved.