Home > Mobile >  check if row value value is equal to column name and access the value of the column
check if row value value is equal to column name and access the value of the column

Time:09-24

Sample dataframe -

col1 col2 col3 col4 colfromvaluestobepicked new col
1 1 0 1 'col1' 1
0 0 1 1 'col2' 0

I want to create a new column whose values are based on if the colfromvaluestobepicked ('col1') is col1 then pick that col value and assign it to the new col and so on.

I am not sure how to achieve this?

CodePudding user response:

try this:

df['new col'] = df.apply(lambda row: row[row['colfromvaluestobepicked']],axis =1)

CodePudding user response:

Use DataFrame.melt for alternative for lookup:

df1 = df.melt('colfromvaluestobepicked', ignore_index=False)

df['new']=df1.loc[df1['colfromvaluestobepicked'].str.strip("'") == df1['variable'],'value']
  • Related