mhaz
mhaz

Reputation: 3

numpy : Want to extract a column, gives a row

I came from MATLAB to Python and I face some problems dealing with matrices.

So, I have a matrix (implemented as a np.array) and I want to manipulate columns of that matrix.

So, I begin with an initialization :

x = np.nan * np.ndarray((2,8))
y = np.nan * np.ndarray((2,8))

which give two

array([[ nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan],
   [ nan,  nan,  nan,  nan,  nan,  nan,  nan,  nan]])

Now, I want to put a column vector v inside y to compute something inside x later

v = np.array([[v1, v2]]) # if v = np.array([[v1], [v2]], doesn't compute on next line
y[:,0] = np.copy(v)
x[:,0] = y[:,0] + someRandomVector

It returns to me an error :

ValueError: could not broadcast input array from shape (2,2) into shape (2)

I think the problem comes from the fact that x[:,0] does not give a column vector as I expected but rather

>>> x[:,0]
array([ nan,  nan])

Any idea or tips that might help?

Upvotes: 0

Views: 1769

Answers (2)

Troll
Troll

Reputation: 1925

Subsetting is another approach to consider.

>>> x[:, [0]].shape
(2, 1)

You can refer to my other answer for more information.

Upvotes: 0

TommasoF
TommasoF

Reputation: 825

>>>x[:,0:1] 
print x.[:,0:1].shape
(2,1)

In this post is explained the motivation and how the array is managed in numpy.

What this means for your case is that when you write X[:,4], you have one slice notation and one regular index notation. The slice notation represents all indices along the first dimension (just 0 and 1, since the array has two rows), and the 4 represents the fifth element along the second dimension. Each instance of a regular index basically reduces the dimensionality of the returned object by one, so since X is a 2D array, and there is one regular index, you get a 1D result. Numpy just displays 1D arrays as row vectors. The trick, if you want to get out something of the same dimensions you started with, is then to use all slice indices, as I did in the example at the top of this post.

If you wanted to extract the fifth column of something that had more than 5 total columns, you could use X[:,4:5]. If you wanted a view of rows 3-4 and columns 5-7, you would do X[3:5,5:8]. Hopefully you get the idea.

Upvotes: 3

Related Questions