如何将2d numpy数组制作成3d数组?

时间:2011-09-10 14:17:43

标签: python multidimensional-array numpy

我有一个带有形状(x,y)的二维数组,我想将其转换为具有形状(x,y,1)的3d数组。有没有一个很好的Pythonic方法来做到这一点?

8 个答案:

答案 0 :(得分:50)

除了其他答案,您还可以使用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)

答案 1 :(得分:9)

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

答案 2 :(得分:4)

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)

答案 3 :(得分:2)

import numpy as np

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

答案 4 :(得分:2)

希望这个功能可以帮助你将2D数组转换为3D数组。

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)

答案 5 :(得分:0)

如果您只想在(x,y,1)上添加第三个轴(x,y),则Numpy允许您使用dstack命令轻松地做到这一点。

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

您需要对它进行转置(.T才能将其转换为所需的(x,y,1)格式。

答案 6 :(得分:0)

您可以通过重塑来实现

例如,您有一个形状为35 x 750(二维)的数组A,可以使用A.reshape(35,25,30)将形状更改为35 x 25 x 30(三个维度)

文档here

中的更多内容

答案 7 :(得分:0)

简单的方法,带有一些数学运算

首先,您知道数组元素的数量,可以说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)