Home > database >  How to create conditional pandas series/column?
How to create conditional pandas series/column?

Time:07-30

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)

CodePudding user response:

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

CodePudding user response:

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
  • Related