python - 如何使 1d 数组乘以 2d 数组得到 python 的 3d 数组

标签 python arrays matrix

我担心这可能是一个非常愚蠢的问题。但是我找不到解决方案。 我想在不使用循环的情况下在 python 中执行以下操作,因为我正在处理大型数组。 有什么建议吗?

import numpy as np
a = np.array([1,2,3,..., N]) # arbitrary 1d array
b = np.array([[1,2,3],[4,5,6],[7,8,9]]) # arbitrary 2d array
c = np.zeros((N,3,3))
c[0,:,:] = a[0]*b
c[1,:,:] = a[1]*b
c[2,:,:] = a[2]*b
c[3,:,:] = ...
...
...
c[N-1,:,:] = a[N-1]*b

最佳答案

我的答案只使用 numpy 原语,特别是数组乘法(你想做的有一个名字,它是一个外积)。

由于 numpy 的外部乘法函数的限制,我们必须重新整形结果,但这非常便宜,因为不涉及 ndarray 的数据 block .

% python
Python 2.7.8 (default, Oct 18 2014, 12:50:18) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.array((1,2))
>>> b = np.array([[n*m for m in (1,2,3,4,5,6)] for n in (10,100,1000)])
>>> print b
[[  10   20   30   40   50   60]
 [ 100  200  300  400  500  600]
 [1000 2000 3000 4000 5000 6000]]
>>> print np.outer(a,b)
[[   10    20    30    40    50    60   100   200   300   400   500   600
   1000  2000  3000  4000  5000  6000]
 [   20    40    60    80   100   120   200   400   600   800  1000  1200
   2000  4000  6000  8000 10000 12000]]
>>> print "Almost there!"
Almost there!
>>> print np.outer(a,b).reshape(a.shape[0],b.shape[0], b.shape[1])
[[[   10    20    30    40    50    60]
  [  100   200   300   400   500   600]
  [ 1000  2000  3000  4000  5000  6000]]

 [[   20    40    60    80   100   120]
  [  200   400   600   800  1000  1200]
  [ 2000  4000  6000  8000 10000 12000]]]
>>> 

关于python - 如何使 1d 数组乘以 2d 数组得到 python 的 3d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270530/

相关文章:

arrays - 用于沿大矩阵对角线插入 2x2 矩阵的代码的向量化

c++ - 帮助鼠标算法中的对象

python - 迭代 pandas df rows 以根据条件计算新变量

python - 不使用 numpy 获得对角线?

python - 如何在Python中生成powerpoint时知道它是什么形状的数字

c++ - 数组在方括号中增加元素是什么意思?

java - cplex - 矩阵值和索引的最小化和求和

java - 如何使矩阵乘法Java代码更具故障安全性?

python - 使用 Pytest 和 Mock 测试查询数据库的 View

python - 当编码为shift_jis时,使用Python的电子邮件模块解析电子邮件时出错