1

I would like to convert a 2D np.array of np.arrays into a 3D np.array.

I have a 2D numpy array (A) with A.shape = (x,y)

Each cell within A contains a unique 1D numpy array with A[0][0].shape = (z)

I would like to convert A to a 3D numpy array with newA.shape = (x,y,z)

1
  • What's the A.dtype? What's A[0,0].dtype? Commented Jun 1, 2017 at 3:51

2 Answers 2

1

Setup

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,)

Solution

#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)
Sign up to request clarification or add additional context in comments.

2 Comments

Try np.stack(a.flat) as an alternative to your np.array.
You are welcome. Please upvote and accept it as answer if it helps.
0

converting 2d to 3d is a application specific job, each task requires data structure different type conversion. for my app this function was helpful

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)

There are many other functions in numpy also such as np.reshape(), np.eye() #used for creation of arrays ,but can be used experiment on dummy data

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.