首页 > 解决方案 > 如何将 NumPy (k,n,m)-size ndarray 转换为 (k)-size dttype=object ndarray of (n,m)-size ndarrays?

问题描述

我有一个 int 大小 (k,n,m) 的 NumPy ndarray A,表示每个大小为 nxm 像素的 k 个图像。我想将其转换为大小为 (k,) 的 dtype=object ndarray B,其中包含每个单独的图像作为大小 (n,m) 的 ndarray。

我可以使用 for 循环(如下)来做到这一点,但是有没有更优雅/直接的方式?

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)

标签: pythonarraysnumpyobjectdtype

解决方案


你的数组:

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)

A分配给的替代方式B。更短,但不一定更快。

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)

直接分配不起作用;它必须是数组列表,而不是数组:

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,)

另一个答案不起作用:

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)

推荐阅读