RasK
RasK

Reputation: 51

Python mutiply columns in dataframe

my current sample dataframe is as follows

import pandas as pd
from io import StringIO
s = '''\
X1,X2,Y
5,8,1
8,9,1
3,6,1
7,7,1
1,3,1
'''
df = pd.read_csv(StringIO(s))

Which looks as:

   X1  X2  Y
0   5   8  1
1   8   9  1
2   3   6  1
3   7   7  1
4   1   3  1

I want to multiply and add as follows :-

a= which is sum of (X1*y) -all X1 multiplied by respective Y in that row

a=(5*1)+(8*1)+(3*1)+(7*1)+(1*1) =24

b= which is sum of (X2*y) -all X2 multiplied by respective Y in that row

Upvotes: 0

Views: 47

Answers (1)

Code Different
Code Different

Reputation: 93181

The simplest approach is to do it manually:

a = (df['X1'] * df['Y']).sum() # 24
b = (df['X2'] * df['Y']).sum() # 33

If you have a lot of columns to multiply by Y, you may want to take advantage of numpy's array broadcasting:

(df[['X1', 'X2']] * df['Y'].values[:, None]).sum()

Result:

X1    24
X2    33
dtype: int64

Upvotes: 2

Related Questions