python - Pandas 使用跨多个列的字典值相乘

标签 python pandas numpy

给定以下数据框:

import pandas as pd
df = pd.DataFrame({
    'a': [1,2,3,4,5],
    'b': [5,4,3,3,4],
    'c': [3,2,4,3,10],
    'd': [3, 2, 1, 1, 1]
})

以及以下参数列表:

params = {'a': 2.5, 'b': 3.0, 'c': 1.3, 'd': 0.9}

生成以下所需的输出:

   a  b   c  d  output
0  1  5   3  3    24.1
1  2  4   2  2    21.4
2  3  3   4  1    22.6
3  4  3   3  1    23.8
4  5  4  10  1    38.4

我一直在用它来产生结果:

df['output'] = [np.sum(params[col] * df.loc[idx, col] for col in df)
                 for idx in df.index]

但是,这是一种非常缓慢的方法,我认为必须有更好的方法来使用内置的 pandas 功能。

我也想到了这个:

# Line up the parameters
col_sort_key = list(df)
params_sorted = sorted(params.items(), key=lambda k: col_sort_key.index(k[0]))

# Repeat the parameters *n* number of times
values = [v for k, v in params_sorted]
values = np.array([values] * df.shape[0])

values
array([[ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9],
       [ 2.5,  3. ,  1.3,  0.9]])

# Multiply and add
product = df[col_sort_key].values * values
product
array([[  2.5,  15. ,   3.9,   2.7],
       [  5. ,  12. ,   2.6,   1.8],
       [  7.5,   9. ,   5.2,   0.9],
       [ 10. ,   9. ,   3.9,   0.9],
       [ 12.5,  12. ,  13. ,   0.9]])

np.sum(product, axis=1)
array([ 24.1,  21.4,  22.6,  23.8,  38.4])

但这似乎有点令人费解!对本地 Pandas 有什么想法吗?

最佳答案

您可以使用 assign + mul + sum :

df1 = df.assign(**params).mul(df).sum(1)
print (df1)
0    24.1
1    21.4
2    22.6
3    23.8
4    38.4
dtype: float64

dot + 系列构造函数:

df1 = df.dot(pd.Series(params))
print (df1)
0    24.1
1    21.4
2    22.6
3    23.8
4    38.4
dtype: float64

关于python - Pandas 使用跨多个列的字典值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927695/

相关文章:

python 和json.dump : how to make inner array in one line

Python:无法格式化 SQL 查询字符串

python - 在 Pandas 中使用逗号将整列整数转换为千位分隔的字符串

arrays - 索引错误 : index 10 is out of bounds for axis 0 with size 10

python - key 错误 : "None of [Float64Index([34.62365962451697, 30.28671076822607, 35.84740876993872], dtype=' float6 4')] are in the [columns]"

python - wxPython - 应用程序更新程序

python - 在 Windows 10 上使用 pip 安装 numpy for python 3.7

python - 在 2D numpy 矩阵中查找特定点距离 1 内的所有点

python - 首先根据长度对字符串元素列表进行排序,然后根据字母顺序对长度匹配的元素进行排序

python - Pandas 原始数据框已更改