Skip to content Skip to sidebar Skip to footer

Np.array() Is Not Working When I Gave A List Including Two Ndarray With Different Shape

This is a code. I made a list including two ndarray with different shape. d = [] a = np.arange(183).reshape(3,61) b = np.arange(51).reshape(3,17) d = [a,b] np.array(d) Error i

Solution 1:

As matrices are of different dimensions

> a = np.arange(183).reshape(3,61) b = np.arange(51).reshape(3,17)> d=[np.array(a),np.array(b)]> print(d) for output> 
> or  d=[a,b]>  np.concatenate(d, axis=1)

Solution 2:

When you try to make an array from arrays there are three possible results:

If the arrays have the same shape, the result is a higher dimension array:

In [295]: np.array((np.zeros((2,3),int),np.ones((2,3),int)))                 
Out[295]: 
array([[[0, 0, 0],
        [0, 0, 0]],

       [[1, 1, 1],
        [1, 1, 1]]])
In [296]: _.shape                                                            
Out[296]: (2, 2, 3)

If the arrays differ in shape, the result could be an object dtype array (similar to a list):

In [298]: np.array((np.zeros((2,3),int),np.ones((3,3),int)))                 
Out[298]: 
array([array([[0, 0, 0],
       [0, 0, 0]]),
       array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])], dtype=object)    # shape (2,)

But for some combinations of shapes, the result is an error:

In [301]: np.array((np.zeros((2,3),int),np.ones((2,4),int)))                 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent calllast)
<ipython-input-301-d67e6685581d>in<module>----> 1 np.array((np.zeros((2,3),int),np.ones((2,4),int)))

ValueError: could not broadcast input arrayfrom shape (2,3) into shape (2)

In the error case, the first dimensions match, just as in your first case.

Sometimes to create an object array you have to start with a 'empty' one, and fill it. This is more reliable than the np.array(...) approach.

In [303]: arr = np.empty(2, object)                                          
In [304]: arr[:] = np.zeros((2,3),int),np.ones((2,4),int)                    
In [305]: arr                                                                
Out[305]: 
array([array([[0, 0, 0],
       [0, 0, 0]]),
       array([[1, 1, 1, 1],
       [1, 1, 1, 1]])], dtype=object)
In [306]: arr[:] = np.zeros((2,3),int),np.ones((2,3),int)                    
In [307]: arr                                                                
Out[307]: 
array([array([[0, 0, 0],
       [0, 0, 0]]),
       array([[1, 1, 1],
       [1, 1, 1]])], dtype=object)

Solution 3:

Instead of using np.copy(), I chose to use copy.deepcopy(). It works even if the first shape of two items in list are same.

Post a Comment for "Np.array() Is Not Working When I Gave A List Including Two Ndarray With Different Shape"