chopper draw lion4
chopper draw lion4

Reputation: 13487

Using range while fancy indexing?

Can someone explain this expression to me in simple terms? How could you take a range of two values and set them to zero?

lena_image[range(xmax), range(ymax)] = 0

Upvotes: 1

Views: 320

Answers (2)

zhangxaochen
zhangxaochen

Reputation: 33997

range(n) generates a list ranging from 0 inclusive to n exclusive:

In [847]: range(3)
Out[847]: [0, 1, 2]

and numpy fancy indexing takes the elements at indices Xs and Ys , and assign a new value to them:

In [856]: d
Out[856]: 
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

In [857]: d[range(5), range(5)]=2 #assigns elems on diagonal d[0,0], d[1,1], d[2,2], etc.
     ...: print d
[[ 2.  0.  0.  0.  0.]
 [ 0.  2.  0.  0.  0.]
 [ 0.  0.  2.  0.  0.]
 [ 0.  0.  0.  2.  0.]
 [ 0.  0.  0.  0.  2.]]

Note that there must be the same numbers of Xs and Ys in this case

If you want to modify a block (not diagonal this time), use broadcasting:

In [878]: arange(3)[:, None] #get a 2D array of shape (3, 1)
Out[878]: 
array([[0],
       [1],
       [2]])

In [874]: d[arange(3)[:, None], arange(2)] #get the sub array of row 0~2, col 0~1
Out[874]: 
array([[ 2.,  0.],
       [ 0.,  2.],
       [ 0.,  0.]])

In [875]: d[arange(3)[:, None], arange(2)]=100 #assign new values element-wise 

In [876]: d
Out[876]: 
array([[ 100.,  100.,    0.,    0.,    0.],
       [ 100.,  100.,    0.,    0.,    0.],
       [ 100.,  100.,    2.,    0.,    0.],
       [   0.,    0.,    0.,    2.,    0.],
       [   0.,    0.,    0.,    0.,    2.]])

Upvotes: 2

Steinar Lima
Steinar Lima

Reputation: 7821

Your code will set the main diagonal to zero:

import numpy as np

n = 5
lena_image = np.ones(shape=(n, n))
lena_image[range(n), range(n)] = 0
print lena_image

Out:

[[ 0.  1.  1.  1.  1.]
 [ 1.  0.  1.  1.  1.]
 [ 1.  1.  0.  1.  1.]
 [ 1.  1.  1.  0.  1.]
 [ 1.  1.  1.  1.  0.]]

Upvotes: 2

Related Questions