Reputation: 781
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.
Upvotes: 1
Views: 1030
Reputation: 231415
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]])
Upvotes: 2
Reputation: 3722
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]]
Upvotes: 2