I have a df:
DF
name1 name2 finalName
AB123 BB123 0
BB113 AB113 0
AB343 AB343 0
CC263 BB263 0
ED633 DD633 0
I need to modify finalName in that way:
if name1 starts with AB and name2 starts with BB - finalName should be BB+number so in first case: BB123.
if name1 starts with BB and name2 starts with AB - finalName should be AB+number so in second case: AB123.
In rest of examples finalName should stay 0.
I wrote this code:
for row in range(len(DF)):
if(DF.name1.loc[row][0:2] == 'AB' and DF.name2.loc[row][0:2] == 'BB'):
DF.finalName[row] = DF.name1[row].replace('AB','BB',1)
if(DF.name1.loc[row][0:2] == 'BB' and DF.name2.loc[row][0:2] == 'AB'):
DF.finalName[row] = DF.name1[row].replace('BB','AB',1)
And I got a Key error because I had a missing index (...69,70,72..). So I found info that I need to reindex my df. I done it, and it's work ok. But I also found an info that I shouldn't loop my DF. So my question is:
How can I do it in pandas way? I mean without loop?
PS. final df should looks that:
DF
name1 name2 finalName
AB123 BB123 BB123
BB113 AB113 AB113
AB343 AB343 0
CC263 BB263 0
ED633 DD633 0
DF.finalName[row] = DF.name1[row].replace('AB','BB',1)butDF.finalName[row] = DF.name2[row]?name2, and my answer by['BB' + c, 'AB' + c]wherecis values ofname1without 2 letters. Or someting missing?name1andname2are always same per rows, only different first 2 letters?