Conditional Iteration evaluating a calculated variable against master data

Viewed 22
data = {ID': ['D','R','R','R','R'],
       'Calc_Var': [4,3,12,19,8],
        'Var': [5,5,10,20,20],
        'Adjusted':[5,5,20,20,10]
}

df = pd.DataFrame (data)

print(df)

Looking for an efficient solution to filter on ID (where value = 'R') and then to evaluate 'Calc_var' against 'Var'. 'Var' is essentially master data and has only three values (5, 10, 20). I'm trying to evaluate each row (Calc_var) vs. it's corresponding row (Var) where the logic could be no change, or either an incremental/declining step. The Adjusted_Var would reflect the changes. I drafted a simple DF to illustrate this problem/ outcome. For-loops and iteration are not my best, so I appreciate any help on this one!

1 Answers

If I understand you correctly you want to adjust the Var column according the Calc_Var column. You can use numpy.select for this (I put the result to Adjusted_2 column):

condlist = [df["Calc_Var"] > 10, df["Calc_Var"] > 5, df["Calc_Var"] >= 0]
choicelist = [20, 10, 5]

df["Adjusted_2"] = np.select(condlist, choicelist)
print(df)

Prints:

  ID  Calc_Var  Var  Adjusted  Adjusted_2
0  D         4    5         5           5
1  R         3    5         5           5
2  R        12   10        20          20
3  R        19   20        20          20
4  R         8   20        10          10

If you want to evaluate only ID == 'R' you can use boolean indexing:

m = df.ID.eq("R")

condlist = [
    df.loc[m, "Calc_Var"] > 10,
    df.loc[m, "Calc_Var"] > 5,
    df.loc[m, "Calc_Var"] >= 0,
]
choicelist = [20, 10, 5]

df.loc[m, "Adjusted_3"] = np.select(condlist, choicelist)
print(df)
Related