I have a DataFrame and I want to apply formula on Column A based on Column B.
If Column B has some values then apply formula on column A (100 - column value). Below is the data I have.
DataFrame Input
A B
0 35 TYLER
1 20 MACK
2 30 MACK
3 40 MITCH
If column B has ‘MACK’ and ‘MITCH’ then apply formula, else not. How can I do that?
DataFrame Output
A B
0 35 TYLER
1 80 MACK
2 70 MACK
3 60 MITCH
>Solution :
You can limit your formula to just the matching rows with boolean indexing:
apply_rows = df["B"].isin(["MACK", "MITCH"])
df.loc[apply_rows, "A"] = 100 - df.loc[apply_rows, "A"]