How to conditionally replace a value with a value from the same row in a different column using pandas?

Question:

Say I have a data frame:

ID   X    Y    Z
1    3    5    3
2    1    4    1
3    5    3    5
4    0    7    7

I want column Z to equal column X, unless column X is equal to 0. In that case, I would want column Z to equal column Y. Is there a way to do this without a for loop using pandas?

Asked By: jcholly

||

Answers:

You can try using np.where():

df['Z'] = np.where(df['X'] == 0,df['Y'],df['X'])

Basically this translates to "If X = 0 then use the corresponding value for column Y, else (different than 0) use column X"

Answered By: Celius Stingher

Use a conditional with numpy.where:

df['Z'] = np.where(df['X'].eq(0), df['Y'], df['X'])

Or Series.where:

df['Z'] = df['Y'].where(df['X'].eq(0), df['X'])

Output:

ID   X    Y    Z
1    3    5    3
2    1    4    1
3    5    3    5
4    0    7    7
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.