【问题标题】:Numpy modify multiple values 2D array using slicingNumpy 使用切片修改多个值的二维数组
【发布时间】:2019-01-13 22:34:09
【问题描述】:

我想根据另一个数组的值更改 numpy 二维数组中的一些值。子矩阵的行选择布尔切片,列选择整数切片。

下面是一些示例代码:

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

但是,我唯一得到的是一个例外:

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

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

【问题讨论】:

  • np.ix_ 可以将布尔值转换为正确的索引,b[np.ix_(rows, cols)]。最终结果是答案提供的同一对索引数组 - (5,1) 和 (1,3),它们一起广播以索引 (5,3) 块。

标签: python arrays numpy slice submatrix


【解决方案1】:

你可以使用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.]]

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2020-12-03
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多