【问题标题】:Advanced boolean indexing高级布尔索引
【发布时间】:2021-02-22 09:35:34
【问题描述】:

我想通过掩码选择值并通过使用掩码数组更改值。

代码:

import numpy as np

a = np.zeros((2, 2), dtype=(np.uint8, 3))
x = np.arange(4, dtype=int).reshape((2, 2))

mask = np.logical_and(a1 < 3, a1 > 0)

a[mask] = (1, x[mask], 2)

我想要结果:

a[mask]
>> [[1, 1, 2], [1, 2, 2]]

但我得到错误: ValueError: setting an array element with a sequence.

如果尝试做a[mask] = (1, 2, 2)之类的事情 数组将是

[[[0, 0, 0],
[1, 2, 2]],
[[1, 2, 2],
[0, 0, 0]]]

但我需要使用 x 中的值。 让它看起来像

[[[0, 0, 0],
[1, 1, 3]],
[[1, 2, 3],
[0, 0, 0]]]

我该怎么做?

【问题讨论】:

  • a = np.zeros((2, 2, 3), dtype=np.uint8) 是创建 a 的更清晰的方法。
  • a1 是什么? a 的副本? x?还是隐藏的东西?

标签: python numpy boolean-indexing


【解决方案1】:

可以分两步完成。

import numpy as np 

a = np.zeros((2, 2), dtype=(np.uint8, 3)) 
x = np.arange(4, dtype=int).reshape((2, 2)) 
a1 = x  # Create an a1 for the mask

mask = np.logical_and(a1 < 3, a1 > 0) 

a[mask] = (1, 0, 2)      # Set the outer columns                                         
a[mask, 1] = x[mask]     # Set the column 1

print( a )                                                              
# [[[0 0 0]
#   [1 1 2]]

#  [[1 2 2]
#  [0 0 0]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2017-03-18
    • 2011-11-03
    相关资源
    最近更新 更多