user12691361
user12691361

Reputation:

how to copy values from one column into another column based on conditions of two different columns in pandas?

Hi I am trying to copy values from one column to another column based on conditions. But no luck for it.

Code:


import pandas as pd
df1 = pd.read_csv('file.txt',sep='\t')
id_array = list(df1['ID_1'].unique())

df1['id2_in_id1?'] = df1['ID_2'].apply(lambda a : 'Yes' if a in id_array else 'No')#was trying to create condition for copy

Input:

ID_1    ID_2    branchID         fill?
ABC1               1              yes
DAC1    ABC1                      no
TAC1    ABC1                      no
MAK1    ABC1                      no
TBG1    ABC1                      no
DEF1               2              no
VAX1    DEF1                      no

Expected Output:

ID_1    ID_2    branchID    smallbrancid
ABC1                1            
DAC1    ABC1                     1
TAC1    ABC1                     1
MAK1    ABC1                     1
TBG1    ABC1                     1
DEF1                2             
VAX1    DEF1                     


Upvotes: 0

Views: 87

Answers (1)

BENY
BENY

Reputation: 323226

DO with two mask + ffill

df['smallbrancid']=df.branchID.mask(df.branchID.eq('')).ffill().mask(df.branchID.ne(''),'')
df
Out[37]: 
   ID_1  ID_2 branchID smallbrancid
0  ABC1     -        1            -
1  DAC1  ABC1        -            1
2  TAC1  ABC1        -            1
3  MAK1  ABC1        -            1
4  TBG1  ABC1        -            1
5  DEF1     -        2            -
6  VAX1  DEF1        -            2

Upvotes: 1

Related Questions