i like this post (click again to cancel)
0
i dont like this post (click again to cancel) remove favorite mark from this question (click again to restore mark)

What is the best way, to address a non-contiguous sub-array without using an explicit loop. I have an array, say m = np.arange(16).reshape(4,4) and I am interested in the sub-array with row/column index, say [0,1,3].

One way to address this sub-array is

    >>> import numpy as np
    >>> m = np.arange(16).reshape(4,4)
    >>> idx = [0,1,3]
    >>> m[idx][:,idx]

array([[ 0,  1,  3],
       [ 4,  5,  7],
       [12, 13, 15]])

However, this returns a copy of the sub-matrix and therefore can't be used to assign a value, say 0.

Do i have to use an explicit loop, such as

>>> for i in idx: m[i][:,idx] = 0

or is there a more elegant/faster solution?

Thanks, Kilian

flag offensive
asked 2010-04-17 19:55:21
kilian's gravatar image
1
add comment
1 Answers:
i like this answer (click again to cancel)
0
i dont like this answer (click again to cancel)

Kilian, see ix_ in e.g. cookbook Indexing:

a = np.zeros((3,3))
a[np.ix_([0,1],[0,2])] += 1
print a
# [[ 1.  0.  1.]
#  [ 1.  0.  1.]
#  [ 0.  0.  0.]]
permanent link | flag offensive
asked 2010-05-03 09:45:58
denisb's gravatar image
1
add comment
Your answer:
You are now not logged in but you can answer first and then login
toggle preview

Made with Django.