sometimesiwritecode
sometimesiwritecode

Reputation: 3223

Add n months to a pandas Period object?

This seems like it should be easy but I can find no answer when googling. Say I have some variable k that is of type pandas.Period, and whose value is:

Period('2018-11', 'M')

How do I add n months to this variable. For example if n is 3 i would want k to be

Period('2019-02', 'M')

I have tried the following:

k.month = k.month + 12

But this fails saying:

AttributeError: attribute 'month' of 'pandas._libs.tslibs.period._Period' objects is not writable

Upvotes: 7

Views: 3578

Answers (2)

cs95
cs95

Reputation: 403130

Add a pd.offsets.MonthEnd object:

pd.Period('2018-11', 'M') + pd.offsets.MonthEnd(3)

Upvotes: 6

jezrael
jezrael

Reputation: 863531

Because you add months to month period, only use +:

k = pd.Period('2018-11', 'M')
print (k)
2018-11

k1 = k + 3
print (k1)
2019-02

k2 = k + 12
print (k2)
2019-11

Upvotes: 5

Related Questions