1

Imagine, I have a 2D NumPy array X with 100 columns and 100 rows. Then, how can I extract the following rows and column using indexing?

rows= 1, 5, 15, 16 to 35, 45, 55 to 75
columns = 1, 2, 10 to 30, 42, 50

I know in MATLAB, we can do this using

X([1,5,15,16:35,45,55:75],[1,2,10:30,42,50]). 

How can we do this in Python?

3
  • Does the MATLAB give a block of values? A set of rows and a set of columns? numpy handles the block versus sub2ind cases differently. Commented May 23, 2020 at 3:55
  • yes, as I mentioned in the question, we can extract a set of rows (say indices, idxR) and a set of columns (idxC) simultaneously from an array X in MATLAB using X([idxR], [idxC]). Commented Jun 3, 2020 at 20:11
  • Use np.ix_(list1, list2) to see the kinds arrays needed to index a block. To understand arr[ idx1, idx2] in numpy you have to understand how idx1 broadcasts with idx2. These are the same rules as used when adding two arrays. Commented Jun 3, 2020 at 21:02

1 Answer 1

1

You can use np.r_:

rows = np.r_[1, 5, 15, 16:35, 45, 55:75]
cols = np.r_[1, 2, 10:30, 42, 50]

X[rows,cols]

Note that, in Python, 16:35 usually does not include 35. You may want to do 16:36 if you want row 35 as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.