Home > Software design >  How to conditionally replace a value with a value from the dame row in a different column using pand
How to conditionally replace a value with a value from the dame row in a different column using pand

Time:11-08

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?

CodePudding user response:

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

CodePudding user response:

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"

  • Related