在NumPy中重塑数组

44 投票
3 回答
145603 浏览
提问于 2025-04-17 13:24

考虑一个这样的数组(这只是一个例子):

[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

它的形状是 [9,2]。现在我想把这个数组转换成每一列变成形状 [3,3],像这样:

[[ 0  6 12]
 [ 2  8 14]
 [ 4 10 16]]
[[ 1  7 13]
 [ 3  9 15]
 [ 5 11 17]]

最简单(而且肯定不是“Python风格”)的解决办法是先创建一个合适大小的全零数组,然后用两个循环把数据填进去。我想要一个更符合语言特性的解决方案……

3 个回答

0

这里有两种可能的结果排列方式(参考了@eumiro的例子)。Einops这个工具包提供了一种强大的写法,可以清楚地描述这些操作。

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])
1

numpy有一个很棒的工具可以完成这个任务,叫做“numpy.reshape”,你可以在这里查看它的详细说明:reshape文档链接

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

你还可以使用一个叫“-1”的小技巧

`a = a.reshape(-1,3)`

这个“-1”就像一个通配符,让numpy自己决定要输入的数字,当第二个维度是3的时候

所以没错,这样也可以用: a = a.reshape(3,-1)

还有这样: a = a.reshape(-1,2) 这不会改变任何东西

而这样: a = a.reshape(-1,9) 会把形状改成(2,9)

70
a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答