将2D numpy数组转换为3D数组

时间:2017-06-01 02:17:42

标签: python numpy

我想将np.arrays的2D np.array转换为3D np.array。

我有一个带有A.shape =(x,y)

的2D numpy数组(A)

A中的每个单元格都包含一个唯一的1D numpy数组,其中包含A [0] [0] .shape =(z)

我想使用newA.shape =(x,y,z)将A转换为3D numpy数组

2 个答案:

答案 0 :(得分:0)

<强>设置

a
Out[46]: 
array([[array([5, 5, 4, 2]), array([1, 5, 1, 3]), array([3, 2, 8, 5])],
       [array([3, 5, 7, 3]), array([3, 1, 3, 4]), array([5, 2, 6, 7])]], dtype=object)

a.shape
Out[47]: (2L, 3L)

a[0,0].shape
Out[48]: (4L,)

<强>解决方案

#convert each element of a to a list and then reconstruct a 3D array in desired shape.
c = np.array([e.tolist() for e in a.flatten()]).reshape(a.shape[0],a.shape[1],-1)

c
Out[68]: 
array([[[5, 5, 4, 2],
        [1, 5, 1, 3],
        [3, 2, 8, 5]],

       [[3, 5, 7, 3],
        [3, 1, 3, 4],
        [5, 2, 6, 7]]])

c.shape
Out[69]: (2L, 3L, 4L)

答案 1 :(得分:0)

将2d转换为3d是特定于应用程序的作业, 每个任务都需要数据结构不同的类型转换 对于我的应用程序,此功能很有帮助

def d_2d_to_3d(x, agg_num, hop):

    # alter 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))))

    # convertion of 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)

numpy中还有许多其他函数,例如np.reshape(),np.eye()#用于创建数组,但可用于虚拟数据的实验