Numpy : Want To Extract A Column, Gives A Row
Solution 1:
>>>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.
Solution 2:
Subsetting is another approach to consider.
>>> x[:, [0]].shape
(2, 1)
You can refer to my other answer for more information.
Post a Comment for "Numpy : Want To Extract A Column, Gives A Row"