简体   繁体   中英

Create a new variable on condition of two other variables

I have two binary variables in the dataframe labels:

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,
  2. if target1=1 and target2=0, T=1,
  3. if target1=0 and target2=1, T=2,
  4. if target1=1 and target2=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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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