1

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)

2 Answers 2

2

You can transpose first, then reshape:

table.T.reshape(-1, 1)

array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])
Sign up to request clarification or add additional context in comments.

1 Comment

This is much more concise than my hasty realization.
1

A few more approaches are:


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.