3

I have an array H of dimension MxN, and an array A of dimension M . I want to scale H rows with array A. I do it this way, taking advantage of element-wise behaviour of Numpy

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

It works, but the two swapaxes operations are not very elegant, and I feel there is a more elegant and consise way to achieve the result, without creating temporaries. Would you tell me how ?

Monkey
  • 1,838
  • 1
  • 17
  • 24
  • possible duplicate of [How to normalize a 2-dimensional numpy array in python less verbose?](http://stackoverflow.com/questions/8904694/how-to-normalize-a-2-dimensional-numpy-array-in-python-less-verbose) – LondonRob Mar 26 '15 at 12:08

2 Answers2

5

I think you can simply use 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]])

because None (or newaxis) extends A in dimension (example link):

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]])
DSM
  • 342,061
  • 65
  • 592
  • 494
2

You just need to reshape A so that it will broad cast properly:

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

so:

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]])
tacaswell
  • 84,579
  • 22
  • 210
  • 199