python - 如何在 Numpy 中有效地将二维数组中的每个元素乘以一维数组?

标签 python numpy elementwise-operations

我想使用 numpy 有效地将 2D 数组中的每个元素与 1D 数组相乘,以便返回 3D 数组。

基本上,代码应该执行以下操作:

import numpy as np

#create dummy data
arr1=np.arange(0,9).reshape((3,3))
arr2=np.arange(0,9)

#create output container
out = []

#loop over every increment in arr1
for col in arr1:

    row = []

    for i in col:

        #perform calculation
        row.append(i*arr2)

    out.append(row)


#convert output to array
out = np.array(out)

没有形状 (3, 3, 9),因此等于

array([[[ 0,  0,  0,  0,  0,  0,  0,  0,  0],
        [ 0,  1,  2,  3,  4,  5,  6,  7,  8],
        [ 0,  2,  4,  6,  8, 10, 12, 14, 16]],

       [[ 0,  3,  6,  9, 12, 15, 18, 21, 24],
        [ 0,  4,  8, 12, 16, 20, 24, 28, 32],
        [ 0,  5, 10, 15, 20, 25, 30, 35, 40]],

       [[ 0,  6, 12, 18, 24, 30, 36, 42, 48],
        [ 0,  7, 14, 21, 28, 35, 42, 49, 56],
        [ 0,  8, 16, 24, 32, 40, 48, 56, 64]]])

提前非常感谢您!

最佳答案

使用numpy.outer:

np.outer(arr2,arr1).reshape(3,3,9)

获取:

array([[[ 0,  0,  0,  0,  0,  0,  0,  0,  0],
        [ 0,  1,  2,  3,  4,  5,  6,  7,  8],
        [ 0,  2,  4,  6,  8, 10, 12, 14, 16]],

       [[ 0,  3,  6,  9, 12, 15, 18, 21, 24],
        [ 0,  4,  8, 12, 16, 20, 24, 28, 32],
        [ 0,  5, 10, 15, 20, 25, 30, 35, 40]],

       [[ 0,  6, 12, 18, 24, 30, 36, 42, 48],
        [ 0,  7, 14, 21, 28, 35, 42, 49, 56],
        [ 0,  8, 16, 24, 32, 40, 48, 56, 64]]])

关于python - 如何在 Numpy 中有效地将二维数组中的每个元素乘以一维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59878166/

相关文章:

python - 在 django/python 网络应用程序中包含常见内容(例如标题脚本)的最佳方式是什么

python - 如何获取 Pandas 中具有数值和分类值的列作为单独的列表?

python - 从 python 数组创建元素明智的字典

python - 字符串中的替代字母 - 代码不起作用

python - 返回集合中 ISODate 值的最小值

python - numpy cumsum 函数的反函数是什么?

matlab - 将一个向量的每个元素乘以另一个向量的每个元素

python - 如何计算同一列中的值

python - 我如何正确处理多维 numpy 数组