I have the following data frame
df1 = DataFrame([['OBJ1', 10, 'BX', 'pool1', 'OBJ2'],['OBJ2', 0, '', '', 'OBJ1'],['OBJ3', 10, 'BY', 'pool2', 'OBJ4'],['OBJ4', 0, '', '', 'OBJ3'],['OBJ5', 10, 'BZ', 'pool3', '']], columns=['OBJ', 'value', 'conf', 'Res', 'Key'])
What I am trying to do is to:
I tried multiple solutions using either lookup or some other posts but nothing seems to work.
df1.loc[df1['value']==0, 'conf'] = df1.loc[df1['OBJ']==df1['Key']]['conf']
failed as I realized this is looking for rows with OBJ = Key
Use DataFrame.merge
with left_on
and right_on
parameters and index
column created by DataFrame.reset_index
for new DataFrame
, then convert index
column to index
by DataFrame.set_index
and last set new volumns by DataFrame.loc
:
m = df1['value'].eq(0)
cols = ['conf','Res']
df = (df1.reset_index().loc[m, ['index','OBJ']]
.merge(df1, left_on='OBJ', right_on='Key')
.set_index('index')[cols])
print (df)
conf Res
index
1 BX pool1
3 BY pool2
df1.loc[m, cols] = df
print (df1)
OBJ value conf Res Key
0 OBJ1 10 BX pool1 OBJ2
1 OBJ2 0 BX pool1 OBJ1
2 OBJ3 10 BY pool2 OBJ4
3 OBJ4 0 BY pool2 OBJ3
4 OBJ5 10 BZ pool3