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
CodePudding user response:
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"]
CodePudding user response:
You could also use isin
mask
:
df['A'] = df['A'].mask(df['B'].isin(['MACK','MITCH']), 100-df['A'])
or isin
numpy.where
import numpy as np
df['A'] = np.where(df['B'].isin(['MACK','MITCH']), 100-df['A'], df['A'])
Output:
A B
0 35 TYLER
1 80 MACK
2 70 MACK
3 60 MITCH