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

Create multiple calculated fields which are referenced to other columns, based on conditions using Pandas

I wish to create multiple calculated fields which are referenced to other columns, based on conditions using Pandas

Data

ID       status         used
AA       False          3
BB       True           2

Desired

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

ID       status         used     new
AA       False          3        0.6  
BB       True           2        2

Doing

df['new'] = df.apply(lambda row: row['used'] * 0.2 if row['status'] == 
                                       'False' else row['used'] * 1, axis = 1)

Any suggestion is appreciated
The following is not calculating off of the correct field

>Solution :

With this code:

import pandas as pd

data = {
    'ID': ['AA', 'BB'],
    'status': [False, True],
    'used': [3, 2]
}

df = pd.DataFrame(data)

df['new'] = df.apply(lambda row: row['used'] * 0.2 if row['status'] == False else row['used'] * 1, axis=1)

print(df)

I can create your desired output:

   ID  status  used  new
0  AA   False     3  0.6
1  BB    True     2  2.0
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