Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas sumproduct

I have a df:

Value1  Value2  1   2   3
  1       A     0   1   2
  2       B     3   4   5
  3       C     2   2   2

I want to perform sumproduct between the rows and the columns 1 2 3:

Value1  Value2  1   2   3   sumproduct
  1       A     0   1   2   8    = 0*1 + 1*2 + 2*3
  2       B     3   4   5   26   = 3*1 + 4*2 + 5*3
  3       C     2   2   2   12   = 2*1 + 2*2 + 2*3

I've tried (df.values*df.columns.values).sum(1) but then I need to drop Value1 and Value2 columns first. Is there a better approach?

Many thanks!

like image 775
TylerNG Avatar asked Feb 23 '18 23:02

TylerNG


People also ask

How do you sum aggregate in pandas?

Use DataFrame. groupby(). sum() to group rows based on one or multiple columns and calculate sum agg function. groupby() function returns a DataFrameGroupBy object which contains an aggregate function sum() to calculate a sum of a given column for each group.

How do you find the sum of two columns in pandas?

To sum pandas DataFrame columns (given selected multiple columns) using either sum() , iloc[] , eval() and loc[] functions. Among these pandas DataFrame. sum() function returns the sum of the values for the requested axis, In order to calculate the sum of columns use axis=1 .

Can you sum objects in pandas?

Pandas DataFrame sum() MethodThe sum() method adds all values in each column and returns the sum for each column. By specifying the column axis ( axis='columns' ), the sum() method searches column-wise and returns the sum of each row.


1 Answers

What I will do

df.iloc[:,2:].dot([1,2,3])
Out[239]: 
0     8
1    26
2    12
dtype: int64

To make it automatic

s=df.iloc[:,2:]

s.dot(s.columns.astype(int))
Out[242]: 
0     8
1    26
2    12
dtype: int64
like image 195
BENY Avatar answered Oct 21 '22 20:10

BENY