You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对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, Col3 with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:08:13