gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:17:35 27 4
gpt4 key购买 nike

我想根据另一个数组的值更改 numpy 2D 数组中的某些值。子矩阵的行使用 bool 切片选择,列使用整数切片选择。

这里是一些示例代码:

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)

我想要的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.]]

但是,我得到的唯一结果是一个异常(exception):

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

怎样才能达到我想要的结果?

最佳答案

您可以使用argwhere :

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

b[rows, cols] = 2 # Replace the values with 2
print(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.]]

关于python - Numpy使用切片修改多个值二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173838/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com