Home > Back-end >  Finding the summation of values from two pandas dataframe column
Finding the summation of values from two pandas dataframe column

Time:11-11

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.

CodePudding user response:

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

CodePudding user response:

You can use pandas.DataFrame.shift().

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

# Explanation
>>> df['x']*df['y'].shift(1) - df['x'].shift(1)*df['y']

0      NaN
1    -60.0
2    180.0
3    375.0
4   -100.0
5     10.0
dtype: float64

CodePudding user response:

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()
  • Related