How can I generate a variable conditioning on different columns?

Question:

My dataset:

country_d regime_d country_o regime_o year col_dep_ever col_dep_end_year
Afghanistan 0.0 United Kingdom 1.0 1948 1.0 1919.0
Afghanistan 0.0 United Kingdom 1.0 1949 1.0 1919.0
Afghanistan 0.0 United Kingdom 1.0 1950 1.0 1919.0
India 0.0 United Kingdom 1.0 1948 1.0 1920.0
India 0.0 United Kingdom 1.0 1949 1.0 1920.0
Afghanistan 0.0 United Kingdom 1.0 1950 1.0 1920.0

I would like to generate a variable that is 1 if "col_dep_ever" is 1 & regim_o and regime_d are different (regime_o=! regime_d).

for i in range(len(???)):
    if regime_d[i]== regime_o[i] and col_dep_ever==1:
        df['var1']=2
    elif regime_d[i]!=regime_o[i] and col_dep_ever==1:
        df['var1']=1
    elif regime_d[i]!=regime_o[i] and col_dep_ever==0:
        df['var1']=0
    elif regime_d[i]==regime_o[i] and col_dep_ever==0:
        df['var1']=0
    else:
        df['var1']=None
Asked By: Korkut

||

Answers:

I will give an answer to 1 row, you can generalise it with a loop.
Also based on the 0 lines of code you provided us I had to make some assumption. but this should resolve your issue

## I have no idea why it is not just a boolean but ok
my_binary_data = 1 if col_dep_ever == '1.0' and regime_o=! regime_d else 0

A better way is to just use a True/False value :

my_boolean_value = col_dep_ever == '1.0' and regime_o=! regime_d
Answered By: Farid Fakhry
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.