2

Here is an example of my DataFrame:

X     Y
4.2  3.0
6.8  4.7
8.4  2.1

I would like implement a formula but ran into some errors. I would like find the value for X squared divided by the summation of X squared + Y squared.

The formula would look like this:

Z = X2/(X2 + Y**2)

I would like my new DataFrame to still have the columns 'X' and 'Y' but also have a new column 'Z' which would contain the output from my formula. The 'Z' column would apply the formula to each row.

X     Y    Z
4.2  3.0  .58
6.8  4.7  .59
8.4  2.1   .8

I tried using the formula below but it did not work:

df['Z'] = (df['X']**2/(df['X']**2 + df['Y']**2)
Able Archer
  • 579
  • 5
  • 19
  • `(df['X']**2/(df['X']**2 + df['Y']**2))` produces exactly the same thing as the answer below. Why does it not work for you? Obviously you're missing a closing brace, but I'm assuming your problem isn't that trivial. – cs95 Dec 16 '19 at 23:52
  • 1
    he wants `mul` @cs95, I have checked the output – ansev Dec 16 '19 at 23:57

1 Answers1

3

Use:

df['Z'] = df['X'].mul(2)/( df['X'].mul(2) + df['Y'].mul(2) )
#df['Z'] = df['X']*2/( df['X']*2 + df['Y']*2 )

or

df['Z'] = df['X'].mul(2)/df.mul(2).sum(axis=1)

#If you want select the columns
#df['Z'] = df['X'].mul(2)/df[['X','Y']].mul(2).sum(axis=1) 

Output:

     X    Y         Z
0  4.2  3.0  0.583333
1  6.8  4.7  0.591304
2  8.4  2.1  0.800000
ansev
  • 30,322
  • 5
  • 17
  • 31