How to Normalize a 2-Dimensional Numpy Array in Python Less Verbose

How to normalize a 2-dimensional numpy array in python less verbose?

Broadcasting is really good for this:

row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]

row_sums[:, numpy.newaxis] reshapes row_sums from being (3,) to being (3, 1). When you do a / b, a and b are broadcast against each other.

You can learn more about broadcasting here or even better here.

Numpy normalize multi dim (>=3) array

Sum along the last axis by listing axis=-1 with numpy.sum, keeping dimensions and then simply divide by the array itself, thus bringing in NumPy broadcasting -

a/a.sum(axis=-1,keepdims=True)

This should be applicable for ndarrays of generic number of dimensions.

Alternatively, we could sum with axis-reduction and then add a new axis with None/np.newaxis to match up with the input array shape and then divide -

a/(a.sum(axis=-1)[...,None])

Normalizing a numpy array

You can do 1) like that:

array /= array.sum(axis=1, keepdims=True)

and 2) like that:

array = array.astype(float)

Row-wise scaling with Numpy

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]])

Sum rows in 2d numpy

Try this:

myNP_weight = (myNP/myNP.sum(axis=1).reshape(-1,1)).round(3)

Or

myNP_weight = (myNP/myNP.sum(axis=1)[:, None]).round(3)

Output:

>>> print(myNP_weight)
array([[0.625, 0.25 , 0.125],
[0.333, 0.333, 0.333],
[0.333, 0.333, 0.333]])


Related Topics



Leave a reply



Submit