Pandas Compare two column and getting another column with three diffrent inference according to condition

Viewed 37

Hello I have dataframe with two column wanted to put some condition in column to create another column in a dataframe. condition will be according to values present in the column1 or second

dataframe example:

    stage   21_A_ex1    21_B_ex2
    stage1       0         1
    stage2      0.55     0.45
    stage3      0.66     0.34
    stage4      0.87     0.13
    stage5      0.63     0.37
    stage6         1     0
    stage7      0.95     0.05
    stage8      0.97     0.03
    stage9      0.02     0.98

my conditions are column1 <=0.95 and > 0.05 new column value will be "BOTH", value > 0.95 new column value will be "ex1" if value < 0.05 new column value ex2

df.column[1] <= 0.95 and >0.05 BOTH

df.column[1] > 0.95 ex1

df.column[1] < 0.05 ex2

output

    stage   2131_A_ex1  2131_B_ex2    2131
    stage1       0         1          ex2
    stage2      0.55     0.45         BOTH
    stage3      0.66     0.34         BOTH
    stage4      0.87     0.13         BOTH
    stage5      0.63     0.37         BOTH
    stage6         1     0             ex1
    stage7      0.95     0.05         BOTH
    stage8      0.97     0.03          ex1
    stage9      0.02     0.98          ex2

I tried below command but didnt get my output I know I didnot put all condition in below command. any one help me how can I put other condition to get my output

df['Type'] = df.apply(lambda x: "BOTH" if x["21_A_ex1"] <= 0.95 else "ex1", axis=1)
1 Answers

You should use np.select

import numpy as np

c1 = (0.05 < df["21_A_ex1"]) & (df["21_A_ex1"] <= 0.95 )
c2 = df["21_A_ex1"] <= 0.05

df['Type'] = np.select([c1, c2], ['BOTH', 'ex2'], 'ex1')

Out[148]:
    stage  21_A_ex1  21_B_ex2  Type
0  stage1      0.00      1.00   ex2
1  stage2      0.55      0.45  BOTH
2  stage3      0.66      0.34  BOTH
3  stage4      0.87      0.13  BOTH
4  stage5      0.63      0.37  BOTH
5  stage6      1.00      0.00   ex1
6  stage7      0.95      0.05  BOTH
7  stage8      0.97      0.03   ex1
8  stage9      0.02      0.98   ex2
Related