Red Beam
Red Beam

Reputation: 75

Python ValueError while dividing array by its own column

Numpy arrays A = [[1, 2, 3, 4], [1, 2, 3, 4 ]] and C = A[:,1]. B should be A/C. I am expecting B to be [[0.5, 1, 1.5, 2], [0.5, 1, 1.5, 2]] I am trying to do the same using normal division, or numpy division, but get an error, ValueError: operands could not be broadcast together with shapes (2,4) (2,). It is dividing an entire array with a column in that particular array. Any suggestions? There is a similar post, but no solid answers to it.

Upvotes: 5

Views: 1480

Answers (2)

unutbu
unutbu

Reputation: 880269

NumPy broadcasts by adding new axes on the left. If you want to add a new axis on the right, you must do so manually:

B = A/C[:, np.newaxis]

A has shape (2,4) and C has shape (2,). We need C to have shape (2,4) for A/C to make sense. If we add a new axis on the right-hand-side to C, then C would have shape (2,1) which NumPy then broadcasts to shape (2,4) upon division with A.


In [73]: A = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])

In [74]: C = A[:,1]

In [75]: A.shape
Out[75]: (2, 4)

In [76]: C.shape
Out[76]: (2,)

In [77]: B = A/C[:, np.newaxis]

In [78]: B
Out[78]: 
array([[0, 1, 1, 2],
       [0, 1, 1, 2]])

As NumPy broadcasts by adding new axes on the left. If you want to add a new axis on the right, you must do so manually:

B = A/C[:, np.newaxis]

A has shape (2,4) and C has shape (2,). We need C to have shape (2,4) for A/C to make sense. If we add a new axis on th right-hand-side to C, then C would have shape (2,1) which NumPy then broadcasts to shape (2,4) upon division with A.


In [73]: A = np.array([[1, 2, 3, 4], [1, 2, 3, 4 ]])

In [74]: C = A[:,1]

In [75]: A.shape
Out[75]: (2, 4)

In [76]: C.shape
Out[76]: (2,)

In [77]: B = A/C[:, np.newaxis]

In [78]: B
Out[78]: 
array([[0, 1, 1, 2],
       [0, 1, 1, 2]])

As Ashwini Chaudhary shows, convert A (or C) to a float dtype to make NumPy perform floating-point division:

In [113]: A.astype(float)/C[:, np.newaxis]
Out[113]: 
array([[ 0.5,  1. ,  1.5,  2. ],
       [ 0.5,  1. ,  1.5,  2. ]])

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251051

To make broadcasting possible here add one more axis to C:

>>> A = np.array([[1, 2, 3, 4], [1, 2, 3, 4 ]], dtype=float)
>>> C = A[:,1][:, None]
>>> A/C
array([[ 0.5,  1. ,  1.5,  2. ],
       [ 0.5,  1. ,  1.5,  2. ]])

Upvotes: 5

Related Questions