Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy rank 1 arrays

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))

like image 753
NeuroMonk Avatar asked Apr 11 '16 10:04

NeuroMonk


People also ask

What is a rank 1 array in Python?

It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy dimensions are called axes. The number of axes is rank. For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis.

How do you rank items in an array NumPy?

To rank items in NumPy, we can use a special method called numpy. argsort() . In the numpy. argsort() method, indices are used to sort arrays in NumPy.

What is the 1 axis in NumPy?

Axis 1 is the direction along the columns In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns.

What is an array rank?

The rank of an array is the number of dimensions it has. A scalar is considered to have rank zero.


1 Answers

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

like image 127
1'' Avatar answered Oct 06 '22 18:10

1''