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 choose a value from two columns (First and Second) to subtract from another column (Third), based on condition?

enter image description here

There are 4 columns in total.

VALUE_DIFF is the calculated value. This is based on if column "SECOND" has a value greater than 0, then subtract column value from "SECOND" and "BASE_COLUMN" [ SECOND – BASE_COLUMN]. If column "SECOND" is 0 then subtract column value from "FRIST" and "BASE COLUMN" [FIRST – BASED_COLUMN]

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

Wondering how can Pandas execute with this condition?

>Solution :

Use numpy.where:

df['DIFF'] = np.where(df['SECOND'].gt(0), df['SECOND'], df['FIRST']) - df['BASE_COLUMN']

What is same like:

df['DIFF'] = np.where(df['SECOND'].gt(0), 
                      df['SECOND']- df['BASE_COLUMN'], 
                      df['FIRST']- df['BASE_COLUMN']) 
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