Thursday, April 11, 2019

Reshaping NumPy Arrays into Columns

$ x = np.arange(5)
$ x
array([0, 1, 2, 3, 4])

Two different methods:

$ x.reshape(-1,1)
array([[0],
       [1],
       [2],
       [3],
       [4]])

$ np.c_[x]
array([[0],
       [1],
       [2],
       [3],
       [4]])

2 comments:

Anonymous said...

Another common method I have seen is

x[:,np.newaxis]

I first read about this method in The Python Data Science Handbook by Jake VanderPlas

Sachin Shanbhag said...

Thanks, I never used that one before.