gpt4 book ai didi

python - Pandas 比较两列并根据条件获得具有三种不同推理的另一列

转载 作者:行者123 更新时间:2023-12-04 09:24:28 24 4
gpt4 key购买 nike

你好我有两列的数据框想要在列中放置一些条件以在数据框中创建另一列。条件将根据 column1 或 second 中存在的值
数据框示例:

    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
我的条件是 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 和 >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

关于python - Pandas 比较两列并根据条件获得具有三种不同推理的另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63044432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com