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:

  1. 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

    ReplyDelete
  2. Thanks, I never used that one before.

    ReplyDelete