将3维numpy数组展平

6
如何将此内容展平:
b = np.array([
    [[1,2,3], [4,5,6], [7,8,9]],
    [[1,1,1],[2,2,2],[3,3,3]]
])

into:

c = np.array([
    [1,2,3,4,5,6,7,8,9],
    [1,1,1,2,2,2,3,3,3]
])

这两个都不起作用:

c = np.apply_along_axis(np.ndarray.flatten, 0, b)
c = np.apply_along_axis(np.ndarray.flatten, 0, b)

只返回相同的数组。

最好能够原地展开此数组。

3个回答

8
这将完成任务:
c=b.reshape(len(b),-1)

那么,c就是:
array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

reshape 中的 -1 是什么意思? - dokondr
1
这是一种自动计算该维度大小的快捷方式。由于 b.size = 18len(b) = 2,因此 -1 被计算为 18 / 2 = 9 - Daniel F

2

你可以完全压平然后重新塑形:

c = b.flatten().reshape(b.shape[0],b.shape[1]*b.shape[2])

输出

array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

0

所以你可以随时使用reshape:

b.reshape((2,9)) 
array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接