I have a time series with daily values. I have extracted the month values in column L. I want to add a column (M) with date format. The first value of column ‘M’ is year 2000. I want the value 2000 is repeated if the month is the same, and when we go to the next month the value 2000 becomes 2001 and so on.
This can be done easily in excel by this conditional code:
=IF(L3=L2,M2,M2+366)
But I don’t know how to do that in python.
A code gives you output which you want:
from openpyxl import load_workbook
import datetime
#initial date
m2 = datetime.date(2000, 1, 1)
#get the Book1 excel in python
wb1 = load_workbook('Book1.xlsx')
#select first sheet of the excel
ws1 = wb1.worksheets[0]
#get max row of the excel
MAXROW = ws1.max_row
#loop and apply your function =IF(L3=L2,M2,M2+366) in python
for i in range(2,MAXROW+1):
month = ws1.cell(row=i, column=12).value
monthofnextrow = ws1.cell(row=i+1, column=12).value
if monthofnextrow==month:
ws1.cell(row=i, column=13).value = m2
else:
m2 = m2+datetime.timedelta(days=366)
ws1.cell(row=i, column=13).value = m2
#save the excel file
wb1.save()
Let me know if this helps you😊