To calculate the weighted sum using sumproduct
in pandas, you can use the following code:
import pandas as pd
# Create a dataframe with the values and weights
df = pd.DataFrame({'value': [10, 20, 30, 40], 'weight': [0.1, 0.2, 0.3, 0.4]})
# Calculate the weighted sum
weighted_sum = df['value'].sumproduct(df['weight'])
print(weighted_sum) # Output: 22.0
This will calculate the weighted sum of the value
column using the corresponding weights in the weight
column. The output will be 22.0
, which is the result of (10*0.1) + (20*0.2) + (30*0.3) + (40*0.4)
.
Note that sumproduct
works by multiplying the corresponding elements of the two series and then summing the result. It is equivalent to the following code:
weighted_sum = (df['value'] * df['weight']).sum()