Convert 2d Numpy Array Of Arrays To 3d Array
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
Solution 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 andthen 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)
Solution 2:
converting 2d to 3d is a application specific job, each task requires data structure different type conversion. for my app this function was helpful
defd_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
Post a Comment for "Convert 2d Numpy Array Of Arrays To 3d Array"