Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply formula on a column in Dataframe based on value from other column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading