1

In Python numpy when declaring matrices I use np.array([[row 1], [row 2], . . . [row n]]) form. This is declaring a matrix row-wise. Is their any facility in Python to declare a matrix column-wise? I would expect something like - np.array([[col 1], [col 2], . . . [col n]], parameter = 'column-wise') so that a matrix with n columns is produced.

I know such a thing can be achieved via transposing. But is there a way for np.array([...], parameter = '...') being considered as a row or column based on the parameter value I provide?

***np.array() is just used as a dummy here. Any function with above desired facility will do.

Anirban Chakraborty
  • 539
  • 1
  • 5
  • 15
  • 1
    create the data using `pandas`, column-wise, then do a `to_numpy()` to get numpy array! Or use [`column_stack`](https://numpy.org/doc/stable/reference/generated/numpy.column_stack.html) method. – anurag Jan 15 '21 at 06:56
  • This [SO answer](https://stackoverflow.com/a/8489498/14739759) may be of use! – anurag Jan 15 '21 at 06:58

2 Answers2

2

At the time of array-creation itself, you could use numpy.transpose() instead of numpy.array(), because numpy.tranpose() takes any "array-like" object as input:

my_array = np.transpose ([[1,2,3],[4,5,6]])
print (my_array)

Output:

[[1 4]
 [2 5]
 [3 6]]
fountainhead
  • 3,584
  • 1
  • 8
  • 17
2
In [65]: np.array([[1,2,3],[4,5,6]])
Out[65]: 
array([[1, 2, 3],
       [4, 5, 6]])

There's a whole family of concatenate functions, that help you join arrays in various ways.

stack with default axis behaves much like np.array:

In [66]: np.stack([[1,2,3],[4,5,6]], axis=0)
Out[66]: 
array([[1, 2, 3],
       [4, 5, 6]])

np.vstack also does this.

But to make columns:

In [67]: np.stack([[1,2,3],[4,5,6]], axis=1)
Out[67]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

np.column_stack([[1,2,3],[4,5,6]]) does the same.

transposing is also an option: np.array([[1,2,3],[4,5,6]]).T.

All these '*stack' functions end up using np.concatenate, so it's worth your time to learn to use it directly. You may need to add dimensions to the inputs.

[66] does (under the covers):

In [72]: np.concatenate((np.array([1,2,3])[:,None], np.array([4,5,6])[:,None]),axis=1)
Out[72]: 
array([[1, 4],
       [2, 5],
       [3, 6]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353