在花哨的索引时使用范围? [英] Using range while fancy indexing?

查看:44
本文介绍了在花哨的索引时使用范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以简单地向我解释一下这个表达吗?你怎么能取两个值的范围并将它们设置为零?

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

推荐答案

range(n) 生成范围从 0n 的列表> 独家:

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

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

和 numpy 花式索引获取索引 Xs 和 Ys 处的元素,并为它们分配一个新值:

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.]]

注意在这种情况下必须有相同数量的XY

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

如果你想修改一个block(这次不是对角线),使用broadcasting:

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.]])

这篇关于在花哨的索引时使用范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆