Reputation: 1267
The post, Getting a grid of a matrix via logical indexing in Numpy, is similar, but it does not answer my question since I am working with a one dimensional boolean array.
I am attempting to recreate the following boolean indexing feature in Octave.
octave-3.2.4:6> a = rand(3,3)
a =
0.249912 0.934266 0.371962
0.505791 0.813354 0.282006
0.439417 0.085733 0.886841
octave-3.2.4:8> a([true false true])
ans =
0.24991 0.43942
However, I am unable to create the same results in Python with Numpy.
>>> import numpy as np
>>> a = np.random.rand(3,3)
array([[ 0.94362993, 0.3553076 , 0.12761322],
[ 0.19764288, 0.35325583, 0.17034005],
[ 0.56812424, 0.48297648, 0.64101657]])
>>> a[[True, False, True]]
array([[ 0.19764288, 0.35325583, 0.17034005],
[ 0.94362993, 0.3553076 , 0.12761322],
[ 0.19764288, 0.35325583, 0.17034005]])
>>> a[np.ix_([True, False, True])]
array([[ 0.94362993, 0.3553076 , 0.12761322],
[ 0.56812424, 0.48297648, 0.64101657]])
How do I recreate Octave's boolean indexing on Python with Numpy?
Upvotes: 2
Views: 4346
Reputation: 11644
Two problems:
Indexing with a list [True, False, True]
is not the same as indexing with a boolean array array([True,False,True])
. The list will instead be interpreted as integer indexes [1,0,1]
You need to specify that you only want the results from the first column:
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> mask = np.array([True,False,True])
>>> mask.dtype ## verify we have a bool array
dtype('bool')
>>> a[mask,0]
array([0, 6])
Upvotes: 3