python - 您如何为加权平均平均值迭代地为数据框列赋予权重?

我有一个数据框,其中包含多个具有数字浮点值的列。我想要做的是为每一列赋予分数权重并计算其平均值以存储并将其附加到相同的 df。

假设我们有以下列:s1、s2、s3 我想给他们分别赋予权重:w1,w2,w3

我能够在手头试验所有值时手动执行此操作。但是当我进入列表格式时,它给了我一个错误。 我试图通过迭代来完成它,我在下面附上了我的代码,但它给了我一个错误。我还附上了有效的手动代码,但它需要第一手资料。

无效的代码:

score_df["weighted_avg"] += weight * score_df[feature]

适用但不适用于列表的手动代码:

df["weighted_scores"] = 0.5*df["s1"] + 0.25*df["s2"] + 0.25*df["s3"]

最佳答案

我们可以为此使用 numpy 广播,因为权重与您的列轴具有相同的形状:

# given the following example df
df = pd.DataFrame(np.random.rand(10,3), columns=["s1", "s2", "s3"])

print(df)
    s1   s2   s3
0 0.49 1.00 0.50
1 0.65 0.87 0.75
2 0.45 0.85 0.87
3 0.91 0.53 0.30
4 0.96 0.44 0.50
5 0.67 0.87 0.24
6 0.87 0.41 0.29
7 0.06 0.15 0.73
8 0.76 0.92 0.69
9 0.92 0.28 0.29
weights = [0.5, 0.25, 0.25]
df["weighted_scores"] = df.mul(weights).sum(axis=1)

print(df)
    s1   s2   s3  weighted_scores
0 0.49 1.00 0.50             0.62
1 0.65 0.87 0.75             0.73
2 0.45 0.85 0.87             0.66
3 0.91 0.53 0.30             0.66
4 0.96 0.44 0.50             0.71
5 0.67 0.87 0.24             0.61
6 0.87 0.41 0.29             0.61
7 0.06 0.15 0.73             0.25
8 0.76 0.92 0.69             0.78
9 0.92 0.28 0.29             0.60

https://stackoverflow.com/questions/69094076/

相关文章:

go - 在 golang 中将 []*string 转换为 []string

visual-studio-code - 如何在 VS Code 中按字母顺序排列纯文本列表?

git - 如何创建自定义 git/bash 脚本?

snowflake-cloud-data-platform - 使用 Google 作为身份提供商

python - 根据列表字典python的输入获取名称

javascript - JS : proper way of using optional cha

c++ - 如何区分ascii值和数字?

ruby-on-rails - Rubocop 在 Rails 中的蓝图序列化程序自定义字段中警告

c# - 如何按值列表分组,然后计算每个值的条目数量

swiftui - PresentationMode 触发器 "Variable X used be