Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy divide along axis

Is there a numpy function to divide an array along an axis with elements from another array? For example, suppose I have an array a with shape (l,m,n) and an array b with shape (m,); I'm looking for something equivalent to:

def divide_along_axis(a,b,axis=None):     if axis is None:         return a/b     c = a.copy()     for i, x in enumerate(c.swapaxes(0,axis)):         x /= b[i]     return c 

For example, this is useful when normalizing an array of vectors:

>>> a = np.random.randn(4,3) array([[ 1.03116167, -0.60862215, -0.29191449],        [-1.27040355,  1.9943905 ,  1.13515384],        [-0.47916874,  0.05495749, -0.58450632],        [ 2.08792161, -1.35591814, -0.9900364 ]]) >>> np.apply_along_axis(np.linalg.norm,1,a) array([ 1.23244853,  2.62299312,  0.75780647,  2.67919815]) >>> c = divide_along_axis(a,np.apply_along_axis(np.linalg.norm,1,a),0) >>> np.apply_along_axis(np.linalg.norm,1,c) array([ 1.,  1.,  1.,  1.]) 
like image 906
user545424 Avatar asked Aug 21 '11 19:08

user545424


People also ask

How do you divide each element in a NumPy array?

Dividing a NumPy array by a constant is as easy as dividing two numbers. To divide each and every element of an array by a constant, use division arithmetic operator / . Pass array and constant as operands to the division operator as shown below. where a is input array and c is a constant.

How do you divide a matrix in NumPy?

divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will raise an error.

How do I split a 2D NumPy array?

An array needs to explicitly import the array module for declaration. A 2D array is simply an array of arrays. The numpy. array_split() method in Python is used to split a 2D array into multiple sub-arrays of equal size.

What does NP divide do?

The np. divide() is a numpy library function used to perform division amongst the elements of the first array by the elements of the second array. The process of division occurs element-wise between the two arrays. The numpy divide() function takes two arrays as arguments and returns the same size as the input array.


2 Answers

For the specific example you've given: dividing an (l,m,n) array by (m,) you can use np.newaxis:

a = np.arange(1,61, dtype=float).reshape((3,4,5)) # Create a 3d array  a.shape                                           # (3,4,5)  b = np.array([1.0, 2.0, 3.0, 4.0])                # Create a 1-d array b.shape                                           # (4,)  a / b                                             # Gives a ValueError  a / b[:, np.newaxis]                              # The result you want  

You can read all about the broadcasting rules here. You can also use newaxis more than once if required. (e.g. to divide a shape (3,4,5,6) array by a shape (3,5) array).

From my understanding of the docs, using newaxis + broadcasting avoids also any unecessary array copying.

Indexing, newaxis etc are described more fully here now. (Documentation reorganised since this answer first posted).

like image 188
FredL Avatar answered Nov 13 '22 09:11

FredL


I think you can get this behavior with numpy's usual broadcasting behavior:

In [9]: a = np.array([[1., 2.], [3., 4.]])  In [10]: a / np.sum(a, axis=0) Out[10]: array([[ 0.25      ,  0.33333333],        [ 0.75      ,  0.66666667]]) 

If i've interpreted correctly.

If you want the other axis you could transpose everything:

> a = np.random.randn(4,3).transpose() > norms = np.apply_along_axis(np.linalg.norm,0,a) > c = a / norms > np.apply_along_axis(np.linalg.norm,0,c) array([ 1.,  1.,  1.,  1.]) 
like image 27
Owen Avatar answered Nov 13 '22 07:11

Owen