简体   繁体   English

在其他两个变量的条件下创建一个新变量

[英]Create a new variable on condition of two other variables

I have two binary variables in the dataframe labels:我在 dataframe 标签中有两个二进制变量:

target1=[0,1,0,0,0.....1]
target2=[1,1,0,0,0.....0]

And I want to create a third variable that:我想创建第三个变量:

  1. if target1=0 and target2=0, T=0,如果目标 1=0 和目标 2=0,T=0,
  2. if target1=1 and target2=0, T=1,如果目标 1=1 和目标 2=0,T=1,
  3. if target1=0 and target2=1, T=2,如果目标 1=0 和目标 2=1,T=2,
  4. if target1=1 and target2=1, T=3.如果目标 1=1 且目标 2=1,则 T=3。
for i in range(len(labels)):
    if target1[i]==0 and target2[i]==0:
        labels['T']=0
    elif target1[i]==1 and target2[i]==0:
        labels['T']=1
    elif target1[i]==0 and target2[i]==1:
        labels['T']=2
    else:
        labels['T']=3

for some reason, the only outcome for is 0. I'm not sure what went wrong.出于某种原因,唯一的结果是 0。我不确定出了什么问题。

Probably you need to change可能你需要改变

for i in range(len(labels)):

to

for i in range(len(target1)):

Otherwise you run loop only once or whatever you have items in labels否则,您只运行一次循环或标签中有任何项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM