[Numpy-discussion] Advanced indexing advice?
Cristi Constantin
darkgl0w at yahoo.com
Thu Jun 18 05:03:49 EDT 2009
Good day.
I have a question about advanced indexing.
I have 2 matrices :
>>>
a=array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
b=array([[1, 0, 1],
[0, 2, 0],
[0, 0, 3]])
>>>
I want to put all NON-zero elements from array B into array A, but use offset!
This is how i did:
>>>
mask = b!=0 # Save all non-zero values from B.
offset = (1,1) # Save offset.
bshape = b.shape # Save shape of B.
# Action !
a[ offset[0]:bshape[0]+offset[0], offset[1]:bshape[1]+offset[1] ][ mask ] = b[ mask ]
>>>
After this, a becomes :
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 1, 8, 1, 10, 11],
[12, 13, 2, 15, 16, 17],
[18, 19, 20, 3, 22, 23]])
That's exactly what i want.
Now, my method works, but is very slow when used with big arrays. I use doule indexing, one for offset and one for mask...
Can anyone suggest another method, maybe with advanced indexing to do both the offset and the mask ? I am quite newbie with Numpy.
Or maybe just don't use the mask at all ?
All non-zero values from B must be inserted into A, using offset...
I tried :
a[ offset[0]:bshape[0]+offset[0], offset[1]:bshape[1]+offset[1], mask ] = b[ mask ]
and
a[ mask, offset[0]:bshape[0]+offset[0], offset[1]:bshape[1]+offset[1] ] = b[ mask ]
but both methods transform a into :
array([[ 1, 1, 1, 3, 4, 5],
[ 6, 2, 8, 9, 10, 11],
[12, 13, 3, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
and that's completely wrong.
Any advice is good.
Thank you in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090618/e2241014/attachment.html>
More information about the NumPy-Discussion
mailing list