python - Numpy indexing with a one dimensional boolean array -
the post, getting grid of matrix via logical indexing in numpy, similar, not answer question since working 1 dimensional boolean array.
i attempting recreate following boolean indexing feature in octave.
octave-3.2.4:6> = rand(3,3) = 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, unable create same results in python numpy.
>>> import numpy np >>> = 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 recreate octave's boolean indexing on python numpy?
two problems:
indexing list
[true, false, true]
not same indexing boolean arrayarray([true,false,true])
. list instead interpreted integer indexes[1,0,1]
you need specify want results first column:
>>> = np.arange(9).reshape(3,3) >>> array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> mask = np.array([true,false,true]) >>> mask.dtype ## verify have bool array dtype('bool') >>> a[mask,0] array([0, 6])
Comments
Post a Comment