如何对DataFrame指定列加权求和并新增'Total score'计算列?
Hey there! Let's tackle your two Pandas questions one by one—super straightforward once you see the right approach.
1. How to Calculate a Weighted Sum of Columns in a DataFrame?
Calculating a weighted sum just means multiplying each target column by its corresponding weight and adding the results together. There are a couple of simple, flexible ways to do this:
- Direct Column Arithmetic: The most intuitive method is to write out the calculation explicitly. For example, if you have columns
Col1,Col2,Col3with weights 0.4, 0.3, 0.3 respectively:df['Weighted_Sum'] = df['Col1'] * 0.4 + df['Col2'] * 0.3 + df['Col3'] * 0.3 - Using
dot()Method: If you have a list of weights that match the order of your target columns, you can use matrix multiplication for a cleaner look:weights = [0.4, 0.3, 0.3] # Select the target columns first, then apply dot product df['Weighted_Sum'] = df[['Col1', 'Col2', 'Col3']].dot(weights)
2. Your Specific Case: Calculate Total score from Second & Third Columns
Your requirement is clear: take the second column, add 3 times the third column, and store the result in a new Total score column. The sum() method isn't the right fit here because it just aggregates values—you need to perform a custom weighted calculation instead.
Let's walk through a concrete example with sample data:
Step 1: Create a Sample DataFrame (matching your 5-column structure)
import pandas as pd data = { 'First': [15, 25, 35], 'Second': [7, 10, 14], 'Third': [3, 5, 8], 'Fourth': [2, 4, 6], 'Fifth': [9, 12, 15] } df = pd.DataFrame(data)
Step 2: Calculate the Total score Column
You can do this directly using column names (if you know them):
# Exact logic you described: Second + 3*Third df['Total score'] = df['Second'] + 3 * df['Third']
If you don't have the column names and want to use position (remember, Python uses 0-based indexing—so second column is index 1, third is index 2):
# Use iloc to select columns by position df['Total score'] = df.iloc[:, 1] + 3 * df.iloc[:, 2]
Result
Your DataFrame will now have the new column with values like 7 + 3*3 = 16, 10 + 3*5 = 25, etc.
内容的提问来源于stack exchange,提问作者Nelly Louis

