How to add a date column with a condition?

Question:

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.
Dataset

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.

Asked By: Daniel

||

Answers:

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

Answered By: Devam Sanghvi
m2 = datetime.date(2000, 1, 1)
y = [m2]
for i in range(0,len(df)-1):
    month = df['month'].iat[i]
    monthofnextrow =df['month'].iat[i+1]
    if monthofnextrow==month:
        y.append(m2)
    else:
        m2 = m2+datetime.timedelta(days=366)
        y.append(m2)
df["yearf"] = y  
Answered By: Daniel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.