0

I have a pandas dataframe like below

import pandas as pd
data = [[5, 10], [4, 20], [15, 30], [20, 15], [12, 14], [5, 5]]
df = pd.DataFrame(data, columns=['x', 'y'])

I am trying to attain the value of this expression.

enter image description here

I havnt got an idea how to mutiply first value in a column with 2nd value in another column like in the expression.

3 Answers 3

1

Try pd.DataFrame.shift() but I think you need to enter -1 into shift judging by the summation notation you posted. i + 1 implies using the next x or y, so shift needs to use a negative integer to shift 1 number ahead. Positive integers in shift go backwards.

Can you confirm 320 is the right answer?

0.5 * ((df.x * df.y.shift(-1)) - (df.x.shift(-1) + df.y)).sum()

>>>320
Sign up to request clarification or add additional context in comments.

Comments

1

I think the below code has the correct value in expresion_end

import pandas as pd
data = [[5, 10], [4, 20], [15, 30], [20, 15], [12, 14], [5, 5]]
df = pd.DataFrame(data, columns=['x', 'y'])

df["x+1"]=df["x"].shift(periods=-1)
df["y+1"]=df["y"].shift(periods=-1)
df["exp"]=df["x"]*df["y+1"]-df["x+1"]*df["y"]
expresion_end=0.5*df["exp"].sum()

Comments

1

You can use pandas.DataFrame.shift(). You can one times compute shift(-1) and use it for 'x' and 'y'.

>>> df_tmp = df.shift(-1)
>>> (df['x']*df_tmp['y'] - df_tmp['x']*df['y']).sum() * 0.5
-202.5

# Explanation
>>> df[['x+1', 'y+1']] = df.shift(-1)
>>> df
    x   y   x+1   y+1
0   5  10   4.0  20.0 # x*(y+1) - y*(x+1) = 5*20 - 10*4
1   4  20  15.0  30.0
2  15  30  20.0  15.0
3  20  15  12.0  14.0
4  12  14   5.0   5.0
5   5   5   NaN   NaN

3 Comments

This would give the wrong answer. Should -1 inside shift.
@user16367225, thanks, the answer was edited, I think the final answer is not 320. you can check @Atanas Atanasov's answer too.
I asked @imhans4305 for what the right answer is, no response yet.

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.