numpy数组切片两次 [英] numpy array sliced twice
问题描述
我不确定我为什么不能这样做:
I'm not sure I understand why this doesn't work :
a = np.zeros((10, ))
# first slicing array
pos1 = np.zeros((10, ), dtype=np.bool)
pos1[::2] = True
a[pos1] = 1.
print a
# returns [ 1. 0. 1. 0. 1. 0. 1. 0. 1. 0.]
# second slicing array
pos2 = np.zeros((5, ), dtype=np.bool)
pos2[::2] = True
a[pos1][pos2] = 2.
print a
# still returns [ 1. 0. 1. 0. 1. 0. 1. 0. 1. 0.]
第二个切片为什么不影响整个阵列?
我以为a[pos1]
只是原始数组子部分的视图" ...我缺少什么吗?
why does the second slicing didn't affect the full array?
I thought a[pos1]
was just a "view" of the subpart of the original array... Am I missing something?
(此示例只是一个没有实际用途的简单示例,它只是试图理解原因,因为我使用这种语法的次数很多,但我没想到会得到此结果)
(this example is just a simple example with no real use, it is just to try to understand cause I'm using this kind of syntax a lot and I didn't expect this result)
推荐答案
与最近的您使用的是布尔型掩码,因此a[pos1]
是副本,而不是切片.
You are using a boolean mask, so a[pos1]
is a copy, not a slice.
第一组有效是因为它直接调用__setitem__
:
The first set works because it is a direct call to __setitem__
:
a[pos1] = 1.
a.__setitem__(pos1) = 1
第二个不是因为set
适用于副本a[pos1]
:
The second does not because the set
applies to a[pos1]
, a copy:
a[pos1][pos2] = 2.
a.__getitem__(pos1).__setitem__(pos2)
a[::2][pos2]=3
之所以起作用,是因为a[::2]
是切片-即使它产生的值与a[pos1]
相同.
a[::2][pos2]=3
does work because a[::2]
is a slice - even though it produces the same values as a[pos1]
.
检查某物是副本还是视图的一种方法是查看数组的数据指针
One way to check whether something is a copy or view is to look at the array's data pointer
a.__array_interface__['data']
a[pos1].__array_interface__['data'] # will be different
a[::2].__array_interface__['data'] # should be the same
这篇关于numpy数组切片两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!