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!
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With