Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting first n columns of a numpy matrix

Tags:

python

numpy

I have an array like this:

  array([[-0.57098887, -0.4274751 , -0.38459931, -0.58593526],          [-0.22279713, -0.51723555,  0.82462029,  0.05319973],          [ 0.67492385, -0.69294472, -0.2531966 ,  0.01403201],          [ 0.41086611,  0.26374238,  0.32859738, -0.80848795]]) 

Now I want to extract the following:

   [-0.57098887, -0.4274751]    [-0.22279713, -0.51723555]    [ 0.67492385, -0.69294472]    [ 0.41086611,  0.26374238] 

So basically just first 2 columns..

like image 456
frazman Avatar asked May 16 '12 19:05

frazman


People also ask

How do you select the first column of a NumPy array?

Slice a Range of Values from Two-dimensional Numpy Arrays For example, you can use the index [0:1, 0:2] to select the elements in first row, first two columns. You can flip these index values to select elements in the first two rows, first column.

Which of the following would extract all the first 3 rows of the last 5 columns in a given NumPy 2D array A?

unravel_index(49, (8,8)) on the created array. Slicing Arrays Which of the following would extract all the first 3 rows of the last 5 columns in a given numpy 2D array 'a'? a[ :3 , -5: ] ✓ Correct Feedback: Correct! This would extract the first 3 rows and the last five columns.


2 Answers

If a is your array:

In [11]: a[:,:2] Out[11]:  array([[-0.57098887, -0.4274751 ],        [-0.22279713, -0.51723555],        [ 0.67492385, -0.69294472],        [ 0.41086611,  0.26374238]]) 
like image 199
NPE Avatar answered Sep 22 '22 14:09

NPE


I know this is quite an old question -

A = [[1, 2, 3],      [4, 5, 6],      [7, 8, 9]] 

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3] A_NEW = [[1, 2, 3],          [4, 5, 6]] 

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row,            start_index_column : stop_index_column)] 

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3] 

Reference the numpy indexing and slicing article - Indexing & Slicing

like image 21
yashgarg1232 Avatar answered Sep 21 '22 14:09

yashgarg1232