简体   繁体   English

Numpy 使用切片修改多个值的二维数组

[英]Numpy modify multiple values 2D array using slicing

I want to change some values in a numpy 2D array, based on the values of another array.我想根据另一个数组的值更改 numpy 2D 数组中的某些值。 The rows of the submatrix are selected using boolean slicing and the columns are selected by using integer slicing.使用布尔切片选择子矩阵的行,使用整数切片选择列。

Here is some example code:下面是一些示例代码:

import numpy as np

a = np.array([
    [0, 0, 1, 0, 0],
    [1, 1, 1, 0, 1],
    [0, 1, 0, 1, 0],
    [1, 1, 1, 0, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 0, 0, 0],
])

b = np.ones(a.shape)    # Fill with ones
rows = a[:, 3] == 0     # Select all the rows where the value at the 4th column equals 0
cols = [2, 3, 4]        # Select the columns 2, 3 and 4

b[rows, cols] = 2       # Replace the values with 2
print(b)

The result I want in b is:我在 b 中想要的结果是:

[[1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]
 [1. 1. 1. 1. 1.]
 [1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]]

But, the only thing I get is an exception:但是,我唯一得到的是一个例外:

IndexError
shape mismatch: indexing arrays could not be broadcast together with shapes (5,) (3,)

How could I achieve the result I want?我怎样才能达到我想要的结果?

You could use argwhere :你可以使用argwhere

rows = np.argwhere(a[:, 3] == 0)    
cols = [2, 3, 4]        

b[rows, cols] = 2       # Replace the values with 2
print(b)

Output输出

[[1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]
 [1. 1. 1. 1. 1.]
 [1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]
 [1. 1. 2. 2. 2.]]

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

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