Home > other >  Numpy reshape 3D to 2D column wise
Numpy reshape 3D to 2D column wise

Time:11-23

Given a list of df,the objective is to reshape the df_convert_array into 2D array.

The below snippet does fulfill the objective

alist_df=[pd.DataFrame(np.random.randint(100,size=(4,2))) for _ in range (3)]
arr=np.array(alist_df)
arr_opt=np.array([narr.T.reshape(-1) for narr in arr])

But, the proposed solution require to first transpose and reshape each array in the list.

I thought, the process can be simplified simply as below

arr_opt=arr.T.reshape(3,-1)

However, the output is not as I expect.

May I know how to avoid the use of list-comprehension as describe above?

Remark: Output should be in the form of 2D numpy array

CodePudding user response:

You can also transpose the array, reshape, and then transpose back:

arr_opt = np.reshape(arr.T, (arr.shape[2]*arr.shape[1], -1)).T

(the references to arr.shape are in case you don't know ahead of time what the dimensions of your dataframes are)

CodePudding user response:

In your second example, the transpose operation will permute all three axes before the final reshape, whereas in your first example, only the second two axes are effectively permuted.

Try arr_opt = arr.transpose((1,2)).reshape((3,-1))

  • Related