1

I have a dataframe with 2 columns X and Y. I want to set up a new series which equals X when X=Y, and x/(Y-X) when X!=Y.

If try to do this:

df['temp'] = 0
df.loc[df.X == df.Y, 'temp'] = df.X
df.loc[df.X != df.Y, 'temp'] = df.X /(df.Y-df.X)
Z= df.temp
df = df.drop('temp', axis=1)

I get

ZeroDivisionError: float division by zero

Is there a better way to do this than running loops?

3
  • replace 0 to np.nan Commented Jul 8, 2020 at 21:26
  • still get the same error Commented Jul 8, 2020 at 21:27
  • Your series of operations could be resulting into some though and hence the error Commented Jul 8, 2020 at 22:17

3 Answers 3

1

Data

df=pd.DataFrame({'X':[1,2,3,4,5], 'Y':[2,2,6,4,5]})
df

Use

Import numpy as np
df=df.assign(j=(np.where(df.X==df.Y, df.X, df.X.div(df.Y-df.X))))
df

Sol

 X  Y    j
0  1  2  1.0
1  2  2  2.0
2  3  6  1.0
3  4  4  4.0
4  5  5  5.0
Sign up to request clarification or add additional context in comments.

2 Comments

this seems like the best solution, but somehow not working as in my edit above.
Issue is you dataformat. See stackoverflow.com/questions/7479292/…
1

The condition should apply to both side

df['temp'] = 0
df.loc[df.X == df.Y, 'temp'] = df.X
df.loc[df.X != df.Y, 'temp'] = df.loc[df.X != df.Y,'X'] /(df.loc[df.X != df.Y,'Y']-df.loc[df.X != df.Y,'X'])
Z= df.temp
df = df.drop('temp', axis=1)

Comments

1

Try:

divisor = np.where(df.Y==df.X, 1, df.Y-df.X)

Z = df.X / divisor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.