Home > Mobile >  Convert 1D numpy array to 1D numpy column column, python
Convert 1D numpy array to 1D numpy column column, python

Time:10-12

I am new to python and numpy, I would like to know how to convert 1D array and 2D array into one column: for example:

import numpy as np 
x=np.array([1,2,3,4]) #so I need it to be as:
#x=[1
 #  2
  # 3
   #4]

 y=np.array([[1,2,3]
             [4,5,6]]
 #y=[ 1
 #    4
  #   2
   #  5
    # 3
     #6]

CodePudding user response:

In MATLAB all matrices are 2d (or higher), A column vector has size (n,1). It also has a (:) and (:)' idiom for 'flattening'.

In numpy arrays can be 1d, with shape (n,) (that's a 1 element tuple). But with reshape you can easily make it (n,1) or (1,n). reshape(-1,1) is can be used (does MATLAB allow something like ([],1)` for that?)

Here's an example of playing with your y:

In [112]: y=np.array([[1,2,3],
     ...:              [4,5,6]])
     ...: 
     ...: 
In [113]: y
Out[113]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [114]: y.ravel()
Out[114]: array([1, 2, 3, 4, 5, 6])
In [115]: y.ravel(order='F')          # matlab is fortran order
Out[115]: array([1, 4, 2, 5, 3, 6])
In [116]: y.ravel(order='F')[:,None]
Out[116]: 
array([[1],
       [4],
       [2],
       [5],
       [3],
       [6]])

Note that the nested [] are an essential part of the display. [116] is a (6,1) array.

In [117]: x=np.array([1,2,3,4])
In [118]: x[:,None]
Out[118]: 
array([[1],
       [2],
       [3],
       [4]])
In [119]: x.reshape(-1,1)
Out[119]: 
array([[1],
       [2],
       [3],
       [4]])
  • Related