使用Numpy进行行缩放

时间:2013-02-01 03:13:45

标签: python numpy

我有一个维数为MxN的数组H和一个维数为M的数组A.我想用数组A来缩放H行。我这样做,利用Numpy的元素行为

H = numpy.swapaxes(H, 0, 1)
H /= A
H = numpy.swapaxes(H, 0, 1)

它有效,但两个swapaxes操作不是很优雅,我觉得有一种更优雅和更简洁的方式来实现结果,而不创造临时性。你能告诉我怎么样?

2 个答案:

答案 0 :(得分:5)

我认为你可以简单地使用H/A[:,None]

In [71]: (H.swapaxes(0, 1) / A).swapaxes(0, 1)
Out[71]: 
array([[  8.91065496e-01,  -1.30548362e-01,   1.70357901e+00],
       [  5.06027691e-02,   3.59913305e-01,  -4.27484490e-03],
       [  4.72868136e-01,   2.04351398e+00,   2.67527572e+00],
       [  7.87239835e+00,  -2.13484271e+02,  -2.44764975e+02]])

In [72]: H/A[:,None]
Out[72]: 
array([[  8.91065496e-01,  -1.30548362e-01,   1.70357901e+00],
       [  5.06027691e-02,   3.59913305e-01,  -4.27484490e-03],
       [  4.72868136e-01,   2.04351398e+00,   2.67527572e+00],
       [  7.87239835e+00,  -2.13484271e+02,  -2.44764975e+02]])

因为None(或newaxis)在维度(example link)中扩展A

In [73]: A
Out[73]: array([ 1.1845468 ,  1.30376536, -0.44912446,  0.04675434])

In [74]: A[:,None]
Out[74]: 
array([[ 1.1845468 ],
       [ 1.30376536],
       [-0.44912446],
       [ 0.04675434]])

答案 1 :(得分:2)

您只需要重新塑造A,以便广泛投射:

A = A.reshape((-1, 1))

这样:

In [21]: M
Out[21]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20]])


In [22]: A
Out[22]: array([1, 2, 3, 4, 5, 6, 7])


In [23]: M / A.reshape((-1, 1))
Out[23]: 
array([[0, 1, 2],
       [1, 2, 2],
       [2, 2, 2],
       [2, 2, 2],
       [2, 2, 2],
       [2, 2, 2],
       [2, 2, 2]])