6

Given a 2D numpy array, i.e.;

import numpy as np

data = np.array([
     [11,12,13],
     [21,22,23],
     [31,32,33],
     [41,42,43],         
     ])

I need to both create a new sub-array or modify the selected elements in place based on two masking vectors for the desired rows and columns;

rows = [False, False, True, True]
cols = [True, True, False]

Such that

print subArray

# [[31 32]
#  [41 42]]
1
  • Note that copy and view (as in the title) are very different things. Commented Feb 28, 2013 at 20:05

1 Answer 1

5

First, make sure that your rows and cols are actually boolean ndarrays, then use them to index your data

rows = np.array([False, False, True, True], dtype=bool)
cols = np.array([True, True, False], dtype=bool)
data[rows][:,cols]

Explanation If you use a list of booleans instead of an ndarray, numpy will convert the False/True as 0/1, and interpret that as indices of the rows/cols you want. When using a bool ndarray, you're actually using some specific NumPy mechanisms.

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

1 Comment

Great, thats clear now thanks. Just not as straight-forward as Matlab for same result. I have a follow up - how do I do this in-place, without creating a new array?

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.