Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose a value from a set of columns based on value and create new column with the value?

so if I have a pandas Dataframe like:

   A  B  C  D
0  1  2  3  a 
1  2  4  6  a
2  4  8  8  b
3  2  3  5  c

and want to insert row 'E' by choosing from columns 'A', 'B', or 'C' based on conditions in column 'D', how would I go about doing this? For example: if D == a, choose 'A', else choose 'B', outputting:

   A  B  C  D  E
0  1  2  3  a  1
1  2  4  6  a  2
2  4  8  8  b  8
3  2  3  5  c  3

Thanks in advance!

like image 332
Roy Han Avatar asked Mar 05 '23 03:03

Roy Han


1 Answers

This is lookup

df.lookup(df.index,df.D.str.upper())
Out[749]: array([1, 2, 8, 5], dtype=int64)

df['E']=df.lookup(df.index,df.D.str.upper())
like image 111
BENY Avatar answered May 12 '23 15:05

BENY