如何将一个2维的numpy数组转换为3维数组?

52

我有一个形状为(x, y)的二维数组,我想将其转换为形状为(x, y, 1)的三维数组。有没有一种好的Pythonic方法来实现这个转换?

10个回答

77

除了其他答案外,您还可以使用numpy.newaxis的切片:

>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)

甚至可以使用以下代码(适用于任意维数):

>>> b = a[..., newaxis]
>>> b.shape
(6, 8, 1)

13
顺便提一句,numpy.newaxis 就是 Nonenewaxis 只是为了可读性而存在。等价于这样做 b = a[..., None] (省略号允许其适用于多维数组,而不仅仅是二维数组)。 - Joe Kington
2
真的。由于某种原因,我有这样的印象,即newaxisNone只是一种实现细节(因此可能会在将来更改),但看起来它明确地记录下来了。 - Mark Dickinson
1
假设您想让第三个轴不是1?例如,如何将a转换为b,其中b.shape = (6,8,3) - Gathide
3
这取决于您的需求。您的旧数组包含48个数字,而新数组包含144个数字。您希望如何将原来的48个数字映射到新数组中?要沿第三维重复吗?在这种情况下,大多数时候您不需要重复:将其保留为形状为(6,8,1)并利用NumPy的广播能力即可。但是,如果您确实需要形状为(6,8,3),请查看np.tilenp.broadcast_to - Mark Dickinson
1
如马克·迪金森所说,您可以使用np.broadcast_to来实现此操作,如下所示:b = np.broadcast_to(a[..., np.newaxis], (6, 8, 3)) - wingr
显示剩余3条评论

20
numpy.reshape(array, array.shape + (1,))

谢谢,我使用了 A = A.reshape(A.shape + (1,))。 - nobody
6
如果您愿意就地修改A,您可以简单地将其分配给形状属性: A.shape = A.shape + (1,),甚至是 A.shape += 1, - Mark Dickinson
假设我有一个 3D [1000,10,5] 数组,我想将其转换为形状为[1000, 50]的 2D 数组,类似于连接第二个和第三个初始维度。在这种情况下,使用 reshape 函数可以吗? - seralouk
@serafeim,好的。 - Winston Ewert
1
谢谢。我注意到当我在np.reshape内使用order='F'时,所得到的结果是期望的。如果没有指定order='F',那么在我的情况下输出就是错误的。 - seralouk

13
import numpy as np

# create a 2D array
a = np.array([[1,2,3], [4,5,6], [1,2,3], [4,5,6],[1,2,3], [4,5,6],[1,2,3], [4,5,6]])

print(a.shape) 
# shape of a = (8,3)

b = np.reshape(a, (8, 3, -1)) 
# changing the shape, -1 means any number which is suitable

print(b.shape) 
# size of b = (8,3,1)

4
import numpy as np

a= np.eye(3)
print a.shape
b = a.reshape(3,3,1)
print b.shape

3
希望这个函数能帮助您将二维数组转换为三维数组。
Args:
  x: 2darray, (n_time, n_in)
  agg_num: int, number of frames to concatenate. 
  hop: int, number of hop frames. 

Returns:
  3darray, (n_blocks, agg_num, n_in)


def d_2d_to_3d(x, agg_num, hop):

    # Pad to at least one block. 
    len_x, n_in = x.shape
    if (len_x < agg_num): #not in get_matrix_data
        x = np.concatenate((x, np.zeros((agg_num - len_x, n_in))))

    # main 2d to 3d. 
    len_x = len(x)
    i1 = 0
    x3d = []
    while (i1 + agg_num <= len_x):
        x3d.append(x[i1 : i1 + agg_num])
        i1 += hop

    return np.array(x3d)

2

如果您只想将第三个轴(x,y)添加到(x,y,1),Numpy允许您使用dstack命令轻松完成此操作。

import numpy as np
a = np.eye(3) # your matrix here
b = np.dstack(a).T

你需要对它进行转置 (.T),以便将其转换为你想要的 (x,y,1) 格式。

1
import numpy as np
# create a 2-D ndarray
a = np.array([[2,3,4], [5,6,7]])
print(a.ndim)
>> 2
print(a.shape)
>> (2, 3)

# add 3rd dimension

第一种选择:重新塑形

b = np.reshape(a, a.shape + (1,))
print(b.ndim)
>> 3
print(b.shape)
>> (2, 3, 1)

2nd option: expand_dims

c = np.expand_dims(a, axis=2)
print(c.ndim)
>> 3
print(c.shape)
>> (2, 3, 1)

1
你可以使用reshape来完成这个操作。
例如,如果你有一个形状为35 x 750(两个维度)的数组A,你可以使用A.reshape(35, 25, 30)将其形状改变为35 x 25 x 30(三个维度)。
更多信息请参见文档here

1

用一些数学方法来简单实现

首先,你需要知道数组元素的数量,比如说100个。
然后将100分为3步,例如:

25 * 2 * 2 = 100

或者:4 * 5 * 5 = 100

import numpy as np
D = np.arange(100)
# change to 3d by division of 100 for 3 steps 100 = 25 * 2 * 2
D3 = D.reshape(2,2,25) # 25*2*2 = 100

另一种方法:

another_3D = D.reshape(4,5,5)
print(another_3D.ndim)

给4D:

D4 = D.reshape(2,2,5,5)
print(D4.ndim)

0
如果您有一个数组
a2 = np.array([[1, 2, 3.3],
           [4, 5, 6.5]])

然后您可以使用以下代码将此数组更改为形状为 (2,3,3) 的 3 维数组:

a2_new = np.reshape(a2, a2.shape + (1,)) a2_new

你的输出将是:

array([[[1. ],
    [2. ],
    [3.3]],

   [[4. ],
    [5. ],
    [6.5]]])

或者 你可以尝试:

a2.reshape(2, 3, 1)

这将把你的二维数组转换为三维的shape(2, 3, 1)


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