Why can't I subtract one date period from the next and convert to an integer?

与世无争的帅哥 提交于 2021-02-09 11:10:44

问题


I am trying to determine whether a difference between two months is an even or odd number of months.

I used the command:

import pandas as pd
(pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')) % 2

This seems to work in python 3.6.7, but in another python 3.7.3 environment I get the error:

>>> import pandas as pd
>>> (pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')) % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'MonthEnd' and 'int'

I'm trying to work out what package would make the difference here, or if there is another way to do what I want that would work in both versions?

I took a look at my installed packages and there are a few version differences but I have no idea which would make the difference.

The environment that does not work has python 3.7.3, pandas 0.24.2, and numpy-base 1.16.2. The environment that works has python 3.6.7, pandas 0.22.0, but does not have any version of numpy-base. Both have python-dateutil 2.8.0 and numpy 1.16.2.


回答1:


Problem is Period Subtraction in pandas 0.24+:

Subtraction of a Period from another Period will give a DateOffset. instead of an integer (GH21314)

Solution is attribut .n:

a = (pd.to_datetime('2019-01-01').to_period('m') - pd.to_datetime('2018-08-01').to_period('m'))

print (a)
<5 * MonthEnds>

print (a.n)
5

print (a.n % 2)
1



回答2:


It's because in pandas 0.24.2, it returns:

<5 * MonthEnds>

Which isn't a integer, instead a MonthEnd object, so you would need to do .n, which gives you the actual number of 5:

print((pd.to_datetime('2019-01-01').to_period('M') - pd.to_datetime('2018-08-01').to_period('M')).n % 2)

Which outputs:

1


来源:https://stackoverflow.com/questions/56016233/why-cant-i-subtract-one-date-period-from-the-next-and-convert-to-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!