简体   繁体   English

在由切片和两个布尔数组索引的numpy数组中设置值

[英]Setting values in a numpy arrays indexed by a slice and two boolean arrays

I have two numpy arrays: 我有两个numpy数组:

a = np.arange(100*100).reshape(100,100)
b = np.random.rand(100, 100)

I also have a tuple of slices to extract a certain piece of the array: 我也有一个切片元组来提取数组的某个部分:

slice_ = (slice(5, 10), slice(5, 10))

I then have a set of boolean indices to select a certain part of this slice: 然后,我有一组布尔索引来选择此片的某个部分:

indices = b[slice_] > 0.5

If I want to set these indices to a different value I can do it easily: 如果我想将这些索引设置为其他值,则可以轻松实现:

a[slice_][indices] = 42

However, if I create another set of boolean indices to select a specific part of the indexed array: 但是,如果我创建另一组布尔索引来选择索引数组的特定部分:

high_indices = a[slice_][indices] > 700

and then try and set the value of the array at these indices: 然后尝试在这些索引处设置数组的值:

a[slice_][indices][high_indices] = 42 # Doesn't do anything!

I thought maybe I needed to AND the two index arrays together, but they are different shape: indices has a shape of (5, 5) and high_indices has a shape of (12,) . 我以为可能需要将两个索引数组在一起,但它们的形状不同: indices的形状为(5, 5)high_indices的形状为(12,)

I think I've got myself into a terrible muddle here trying to do something relatively simple. 我想自己陷入了一个混乱的困境,试图做一些相对简单的事情。 How can I index using these two boolean arrays in such a way that I can set the values of the array? 如何以可以设置数组值的方式使用这两个布尔数组建立索引?

Slicing a numpy array returns a view, but boolean indexing returns a copy of an array. 切片numpy数组会返回一个视图,但是布尔索引会返回数组的副本。 So when you indexed it first time with boolean index in a[slice_][indices][high_indices] , you got back a copy, and the value 42 is assigned to a copy and not to the array a . 因此,当您第一次使用a[slice_][indices][high_indices]a[slice_][indices][high_indices]布尔索引对它进行索引时,您将获得一个副本,并且将值42分配给副本而不是数组a You can solve the problem by chaining the boolean index: 您可以通过链接布尔索引来解决问题:

a[slice_][(a[slice_] > 700) & (b[slice_] > 0.5)] = 42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM