Pandas将两列进行比较,并根据条件用三种不同的推理得到另一列



你好,我有一个有两列的数据帧,想在列中设置一些条件,以便在数据帧中创建另一列。条件将根据列1或第二个中的值

数据帧示例:

    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

我的条件是列1<0.95和>0.05的新列值将是"0";两者";,值>0.95的新列值将是"0";ex1";如果值<0.05新列值ex2

df.column[1]<=0.95和>0.05两种

df.column[1]>0.95 ex1

df.column[1]<0.05 ex2

输出

    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

我尝试了低于命令,但没有得到我的输出,我知道我没有把所有的条件都放在低于命令。任何人帮我如何设置其他条件来获得我的输出

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

您应该使用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

最新更新