Home > Net >  How to convert a NumPy (k,n,m)-size ndarray into a (k)-size dttype=object ndarray of (n,m)-size ndar
How to convert a NumPy (k,n,m)-size ndarray into a (k)-size dttype=object ndarray of (n,m)-size ndar

Time:09-17

I have a NumPy ndarray A of size (k,n,m) of int, representing k images each of size nxm pixels. I would like to convert it into a dtype=object ndarray B of size (k,) containing each of the individual images as ndarrays of size (n,m).

I can do it with a for-loop (below), but is there a more elegant/straightforward way?

A = np.arange(2*3*4).reshape(2,3,4)

B = np.empty(A.shape[0],dtype=object)
for i in range(0,A.shape[0]):
    B[i] = A[i]

print(B)

array([array([[ 0,  1,  2,  3],
              [ 4,  5,  6,  7],
              [ 8,  9, 10, 11]]), array([[12, 13, 14, 15],
                                         [16, 17, 18, 19],
                                         [20, 21, 22, 23]])], dtype=object)

CodePudding user response:

Your arrays:

In [37]: A = np.arange(2*3*4).reshape(2,3,4)
    ...: 
    ...: B = np.empty(A.shape[0],dtype=object)
    ...: for i in range(0,A.shape[0]):
    ...:     B[i] = A[i]
    ...: 
In [38]: B
Out[38]: 
array([array([[ 0,  1,  2,  3],
              [ 4,  5,  6,  7],
              [ 8,  9, 10, 11]]), array([[12, 13, 14, 15],
                                         [16, 17, 18, 19],
                                         [20, 21, 22, 23]])], dtype=object)

Alternate way of assigning A to B. Shorter, but not necessarily faster.

In [39]: B[:]=list(A)
In [40]: B
Out[40]: 
array([array([[ 0,  1,  2,  3],
              [ 4,  5,  6,  7],
              [ 8,  9, 10, 11]]), array([[12, 13, 14, 15],
                                         [16, 17, 18, 19],
                                         [20, 21, 22, 23]])], dtype=object)

Direct assignment does not work; it has to be a list of arrays, not an array:

In [41]: B[:]=A
Traceback (most recent call last):
  File "<ipython-input-41-b3ca91787565>", line 1, in <module>
    B[:]=A
ValueError: could not broadcast input array from shape (2,3,4) into shape (2,)

The other answer does not work:

In [42]: np.array([*A], dtype=object)
Out[42]: 
array([[[0, 1, 2, 3],
        [4, 5, 6, 7],
        [8, 9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]], dtype=object)

CodePudding user response:

You could use unpacking instead to get cleaner code:

B = np.array([*A], dtype=object)

EDIT: This does not work as the inner elements also gets turned into object type.

  • Related