Jerrick
Jerrick

Reputation: 61

Search by Index dataframe

I have a column Search that contains string of the header as per:

Alpha Bravo Charlie Search SearchReturn
1      2      3     Alpha      1  
2      5      6     Charlie    6

I am trying to use something like excel Vlookup function for SearchReturn Column.

However, I have no idea how to create the SearchReturn Column, can you advise?

Upvotes: 0

Views: 50

Answers (2)

zipa
zipa

Reputation: 27869

This will do it:

df['SearchReturn'] = df.apply(lambda x: x[x['Search']], axis=1)

Upvotes: 1

jpp
jpp

Reputation: 164653

Use pd.DataFrame.lookup with row and column labels:

df['SearchReturn'] = df.lookup(df.index, df['Search'])

print(df)

   Alpha  Bravo  Charlie   Search  SearchReturn
0      1      2        3    Alpha             1
1      2      5        6  Charlie             6

Upvotes: 3

Related Questions