Numpy array - stack multiple columns into one using reshape

走远了吗. 提交于 2021-02-10 18:54:30

问题


For a 2D array like this:

table = np.array([[11,12,13],[21,22,23],[31,32,33],[41,42,43]])

Is it possible to use np.reshape on table to get an array single_column where each column of table is stacked vertically? This can be accomplished by splitting table and combining with vstack.

single_column = np.vstack(np.hsplit(table , table .shape[1]))

Reshape can combine all the rows into a single row, I'm wondering if it can combine the columns as well to make the code cleaner and possibly faster.

single_row = table.reshape(-1)

回答1:


You can transpose first, then reshape:

table.T.reshape(-1, 1)

array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])



回答2:


A few more approaches are:

  • 1) flattening using Fotran order, followed by explicit promotion as a column vector

  • 2) reshaping using Fortran order, followed by explicit promotion as a column vector


# using approach 1
In [200]: table.flatten(order='F')[:, np.newaxis]
Out[200]: 
array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])

# using approach 2
In [202]: table.reshape(table.size, order='F')[:, np.newaxis]
Out[202]: 
array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])


来源:https://stackoverflow.com/questions/55444777/numpy-array-stack-multiple-columns-into-one-using-reshape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!