简体   繁体   English

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

[英]Multiplying column and row vectors from numpy 2d array with a scalars form a different 1d array

How to multiply each column vector with a scalar from an array? 如何将每个列向量与数组中的标量相乘?

Example

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

How to multiply each row vector with a scalar from an array? 如何将每个行向量与数组中的标量相乘?

Example

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

Recommendations for a better topic will be appreciated 有关更好主题的建议将不胜感激

I prefer the following syntax, which is short, but explicit 我更喜欢以下语法,它很简短但很明确

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. Column multiplication 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. Row multiplication 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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM