TylerNG
TylerNG

Reputation: 941

Panda adding column with if condition

Hi I'm not sure how to add a new column z to my existing df where z = x if x is not 0 else y .

For example:

Name  x  y  |z (new col)
A     1  5  |1
B     2  6  |2
C     0  3  |3
D     0  0  |0

Does np.where apply in this case?

Thanks!

Upvotes: 1

Views: 85

Answers (1)

Lucas Dresl
Lucas Dresl

Reputation: 1170

You can try:

 df['z'] = np.where(df['x']!=0,df['x'],df['y'])

Upvotes: 5

Related Questions