将numpy 2d数组中的列和行向量与来自不同1d数组的标量相乘

时间:2013-05-07 12:59:01

标签: python numpy

如何将每个列向量与数组中的标量相乘?

实施例

a b c                        x1a x2b x3c
a b c     x1 x2 x3      ->   x1a x2b x3c
a b c                        x1a x2b x3c
a b c                        x1a x2b x3c

如何将每个行向量与数组中的标量相乘?

实施例

a a a a                        x1a x1a x1a x1a
b b b b     x1 x2 x3      ->   x2b x2b x2b x2b
c c c c                        x3c x3c x3c x3c

赞赏更好主题的建议

2 个答案:

答案 0 :(得分:4)

我更喜欢以下语法,它很简短,但显式

A = np.ones((3,4))
B = np.arange(3)
print A * B[:,None]

>>> array([[ 0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.]])

A = np.ones((4,3))
B = np.arange(3)
print A * B[None,:]
>>> array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])

答案 1 :(得分:2)

<强> 1。列乘法

In [39]: A = array([[1,2,3],[1,2,3],[1,2,3],[1,2,3]])

In [40]: X = array([10,20,30])

In [41]: A
Out[41]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

In [42]: X
Out[42]: array([10, 20, 30])

In [43]: A * X
Out[43]: 
array([[10, 40, 90],
       [10, 40, 90],
       [10, 40, 90],
       [10, 40, 90]])

<强> 1。行乘法

In [44]: B = array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])

In [45]: B
Out[45]: 
array([[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]])

In [46]: X = array([10,20,30])

In [47]: X
Out[47]: array([10, 20, 30])

In [48]: (B.transpose() * X).transpose()
Out[48]: 
array([[10, 10, 10, 10],
       [40, 40, 40, 40],
       [90, 90, 90, 90]])