Home > Software engineering >  Pandas dataframe: replace value with that of another column based on original value
Pandas dataframe: replace value with that of another column based on original value

Time:11-04

I have a pandas dataframe where I want to replace the value in the Prediction column with the value in the column referred to by the prediction column.

A B C D Prediction
stipulation interrelation jurisdiction interpretation D
typically conceivably tentatively desperately C
familiar imaginative apparent logical A
plan explain study discard B

I have tried a few methods using df.apply() and map() but they haven't worked. The resulting dataframe would look like this:

A B C D Prediction
stipulation interrelation jurisdiction interpretation interpretation
typically conceivably tentatively desperately tentatively
familiar imaginative apparent logical familiar
plan explain study discard explain

CodePudding user response:

# create a dictionary for each row and return the key value of Prediction
df['val']=df.apply(lambda x: x.to_dict( )[x['Prediction']], axis=1)
df

     A          B             C             D              Prediction   val
0   stipulation interrelation jurisdiction  interpretation D            interpretation
1   typically   conceivably   tentatively   desperately    C            tentatively
2   familiar    imaginative   apparent      logical        A            familiar
3   plan        explain       study         discard        B            explain

CodePudding user response:

We used to have lookup ... but it had been removed. One work around

df['new'] = df.values[df.index,df.columns.get_indexer(df.Prediction)]
df
Out[318]: 
             A              B  ... Prediction             new
0  stipulation  interrelation  ...          D  interpretation
1    typically    conceivably  ...          C     tentatively
2     familiar    imaginative  ...          A        familiar
3         plan        explain  ...          B         explain
[4 rows x 6 columns]
  • Related