Numpy rank 1 arrays

NeuroMonk picture NeuroMonk · Apr 11, 2016 · Viewed 9.9k times · Source

I am Matlab/Octave user. Numpy documentation says the array is much more advisable to use rather than matrix. Is there a convenient way to deal with rank-1 arrays, without reshaping it constantly?

Example:

data = np.loadtxt("ex1data1.txt", usecols=(0,1), delimiter=',',dtype=None)
X = data[:, 0]
y = data[:, 1]
m = len(y)

print X.shape, y.shape
>>> (97L, ) (97L, )

I can't add new column to X using concatenate, vstack, append, except np.c_ which is slower, without reshaping X:

X = np.concatenate((np.ones((m, 1)), X), axis = 1)
>>> ValueError: all the input arrays must have same number of dimensions

X - y, couldn't be done without reshaping y np.reshape(y, (-1, 1))

Answer

1'' picture 1'' · Apr 11, 2016

A simpler equivalent to np.reshape(y, (-1, 1)) is y[:, np.newaxis]. Since np.newaxis is an alias for None, y[:, None] also works. It's also worth mentioning np.expand_dims(y, axis=1).