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

operation between columns according to the value it contains

I have a Dataframe that look like this:

df_1:

    Phase_1  Phase_2   Phase_3
0      8       4        2
1      4       6        3
2      8       8        3
3      10      5        8
...

I’d like to add a column called "Coeff" that compute (Phase_max - Phase_min) / Phase_max

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

For the first row: Coeff= (Phase_1 – Phase_3)/ Phase_1 = (8-2)/8 = 0.75

Expected OUTPUT:

df_1

    Phase_1  Phase_2   Phase_3   Coeff
0      8       4        2       0.75
1      4       6        3       0.5
2      8       8        3       0.625
3      10      5        8       0.5

What is the best way to compute this without using loop? I want to apply it on large dataset.

>Solution :

here is one way to do it

# list the columns, you like to use in calculations
cols=['Phase_1', 'Phase_2', 'Phase_3']

# using max and min across the axis to calculate, for the defined columns

df['coeff']=(df[cols].max(axis=1).sub(df[cols].min(axis=1))).div(df[cols].max(axis=1))
df
df
    Phase_1     Phase_2     Phase_3     coeff
0         8           4           2     0.750
1         4           6           3     0.500
2         8           8           3     0.625
3         10          5           8     0.500
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