0

Here is a sample df:

   A B C D E (New Column)
0  1 2 a n ?
1  3 3 p d ?
2  5 9 f z ?

If Column A == Column B PICK Column C's value apply to Column E; Otherwise PICK Column D's value apply to Column E.

I have tried many ways but failed, I am new please teach me how to do it, THANK YOU!

Note: It needs to PICK the value from Col.C or Col.D in this case. So there are not specify values are provided to fill in the Col.E(this is the most different to other similar questions)

2
  • So column E should be n p z, right? Please in the future provide a minimal reproducible example including desired output. For more tips, see How to Ask.
    – wjandrea
    Commented Jul 30, 2022 at 2:50
  • 1
    Got it and will follow the instruction, Thank you for reminding! Commented Jul 30, 2022 at 2:53

2 Answers 2

3

use numpy.where

df['E'] = np.where(df['A'] == df['B'],
                   df['C'],
                   df['D'])
df
    A   B   C   D   E
0   1   2   a   n   n
1   3   3   p   d   p
2   5   9   f   z   z
0
1

Try pandas where

df['E'] = df['C'].where(df['A'].eq(df['B']), df['D'])
df
Out[570]: 
   A  B  C  D  E
0  1  2  a  n  n
1  3  3  p  d  p
2  5  9  f  z  z
1
  • Thank you! it seem 'where' is very important but i never use it... Commented Jul 30, 2022 at 2:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.