Python ValueError when dividing an array into a native column

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

+4
source share
2 answers

To enable translation, add another 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. ]])
+5
source

NumPy , . , :

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

A (2,4) C (2,). C (2,4) A/C, . C, C (2,1), NumPy (2,4) 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]])

NumPy , . , :

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

A (2,4) C (2,). C (2,4) A/C, . C, C (2,1), NumPy (2,4) 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]])

Ashwini Chaudhary, A ( C) float dtype, NumPy :

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

All Articles