6

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
sometimesiwritecode
  • 2,993
  • 7
  • 31
  • 69

2 Answers2

6

Add a pd.offsets.MonthEnd object:

pd.Period('2018-11', 'M') + pd.offsets.MonthEnd(3)
cs95
  • 379,657
  • 97
  • 704
  • 746
5

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252