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
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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.