0

I have a csv file which is below

ID,Name1,Name2
1,A,A
2,B,B
3,C,D
4,0,F
5,0,Z

The new table is below

ID,NewName
1,A
2,B
3,C
4,F
5,Z

Basically if 0 coming in the Name1 has to replace with Name2

1 Answers1

0

You can use replace then do bfill

df['Name']=df.drop('ID',1).replace({'0':np.nan}).bfill(1).iloc[:,0]
df
   ID Name1 Name2 Name
0   1     A     A    A
1   2     B     B    B
2   3     C     D    C
3   4     0     F    F
4   5     0     Z    Z
halfer
  • 19,824
  • 17
  • 99
  • 186
BENY
  • 317,841
  • 20
  • 164
  • 234
  • can you explain Master, instead of bfill(1), can i give bfill('Name1'), or how to give the column name? –  Apr 30 '20 at 13:45
  • @Nons this is mark the 0 as nan in all Names , then we do the bfill, fill from backward, then we just need take the 1st column, we can find the target, since all the NaN value fill by the not null value from nest column, if all the row is 0 you will received NaN at the end. Notice this method is unlimited for how many Names you have , if you have more than 2 like Name1, Name2, Name3 , this method still works – BENY Apr 30 '20 at 13:48
  • @Nons bfill(1) is bfill(axis=1), if you only have two columns you can always do df.Name1.replace({'0':np.nan}).fillna(df.Name2) to assign – BENY Apr 30 '20 at 13:49