Home > OS >  Return entire row and append to value in a dataframe
Return entire row and append to value in a dataframe

Time:04-09

I am trying to write a function that searches a data frame row by row for a values in a column then appends entire row to the right side of the value if that value is found in any row.

Dataframe1

Col1 Col2 Col3 Lookup

400  60    80   90

50   90    68   80

What I want is a following dataframe:

Dataframe 2

Lookup Col1 Col2 Col3

90      50   90   68

80      400  60   80

Any help is much appreciated.

CodePudding user response:

You can try this out;

df1 = df.iloc[:,0:-1]
new = pd.DataFrame()
for val in df['Lookup']:
    s = df1[df1.eq(val).any(1)]
    new = new.append(s,ignore_index = True)
new.insert(0,'Lookup',df['Lookup'])
print(new)

#    Lookup  Col1  Col2  Col3
# 0      90    50    90    68
# 1      80   400    60    80
  • Related