I want to fill a new column by merging two existing columns on specified conditions.
create example df
data = { 'T1': [1,1,1,1,1,2,2,2,2,2],
'T2':[1,2,3,4,1,2,3,4,1,2]}
df = pd.DataFrame(data)
create empty new column
df['new']=''
tried it with a function
def merge(row):
if row['T1']==1 & row['T2']==1:
val='1_1'
elif row['T1']==1 & row['T2']==2:
val='1_2'
elif row['T1']==1 & row['T2']==3:
val='1_3'
elif row['T1']==1 & row['T2']==4:
val='1_4'
elif row['T1']==2 & row['T2']==1:
val='2_1'
elif row['T1']==2 & row['T2']==2:
val='2_2'
elif row['T1']==2 & row['T2']==3:
val='2_3'
else:
val='2_4'
return val
df.loc[:,'new']=df.apply(merge, axis=1)
but getting wrong results
T1 T2 new
1 1 1_1
1 2 2_4
1 3 1_1
1 4 2_4
1 1 1_1
2 2 2_2
2 3 2_2
2 4 2_4
2 1 2_4
2 2 2_2
Can anybody see what I'm doing wrong? Or maybe there is a better way?