how to use if statement with multiple conditions on pandas dataframe

Try This:

import  pandas as pd

data = {
    "YEAR" : [2016,2016,2020,2020,2021,2021,2021,2021,2021,2021,2021,2021,2021,2021],
    "MONTH" : [1,2,4,5,1,2,3,4,5,6,7,8,9,10]
}

df = pd.DataFrame(data)
df.loc[(df["YEAR"] <= 2021) & (df["MONTH"] < 7),"TIME_TYPE"] = "History" 
df.loc[(df["YEAR"] >= 2021) & (df["MONTH"] >= 7),"TIME_TYPE"] = "Forecast" 
print(df)

Result:

    YEAR  MONTH TIME_TYPE
0   2016      1   History
1   2016      2   History
2   2020      4   History
3   2020      5   History
4   2021      1   History
5   2021      2   History
6   2021      3   History
7   2021      4   History
8   2021      5   History
9   2021      6   History
10  2021      7  Forecast
11  2021      8  Forecast
12  2021      9  Forecast
13  2021     10  Forecast

Browse More Popular Posts

Leave a Comment