gpt4 book ai didi

python - 使用 'lookup' 将两个 python 数组相乘

转载 作者:行者123 更新时间:2023-11-28 19:42:33 25 4
gpt4 key购买 nike

import numpy as np
import pandas as pd

columns = ['id', 'A', 'B', 'C']
index = np.arange(3)

df = pd.DataFrame(np.random.randn(3,4), columns=columns, index=index)

weights = {'A': 0.10, 'B': 1.00, 'C': 1.50}

我需要将每个“单元格”中的值乘以相应的权重(不包括第一列)。例如:

df.at[0,'A'] * weights['A']
df.at[0,'B'] * weights['B']

执行此操作并将结果放入新 DataFrame 的最有效方法是什么?

最佳答案

设置

df
Out[1013]:
id A B C
0 -0.641314 -0.526509 0.225116 -1.131141
1 0.018321 -0.944734 -0.123334 -0.853356
2 0.703119 0.468857 1.038572 -1.529723

weights
Out[1026]: {'A': 0.1, 'B': 1.0, 'C': 1.5}

W = np.asarray([weights[e] for e in sorted(weights.keys())])

解决方案

#use a matrix multiplication to apply the weights to each column
df.loc[:,['A','B','C']] *= W
df
Out[1016]:
id A B C
0 -0.641314 -0.052651 0.225116 -1.696712
1 0.018321 -0.094473 -0.123334 -1.280034
2 0.703119 0.046886 1.038572 -2.294584

更新

如果您需要保持列名灵活,我认为更好的方法是将列名和权重保存在 2 个列表中:

columns = sorted(weights.keys())
Out[1072]: ['A', 'B', 'C']

weights = [weights[e] for e in columns]
Out[1074]: [0.1, 1.0, 1.5]

那么你可以这样做:

df.loc[:,columns] *=weights

Out[1067]:
id A B C
0 -0.641314 -0.052651 0.225116 -1.696712
1 0.018321 -0.094473 -0.123334 -1.280034
2 0.703119 0.046886 1.038572 -2.294584

单行解决方案:

df.loc[:,sorted(weights.keys())] *=[weights[e] for e in sorted(weights.keys())]

df
Out[1089]:
id A B C
0 -0.641314 -0.052651 0.225116 -1.696712
1 0.018321 -0.094473 -0.123334 -1.280034
2 0.703119 0.046886 1.038572 -2.294584

关于python - 使用 'lookup' 将两个 python 数组相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44038369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com