简体   繁体   English

如何使用 numpy 布尔数组修改另一个 numpy 数组?

[英]How to use a numpy boolean array to modify another numpy array?

I have a boolean array that looks like this:我有一个如下所示的布尔数组:

arr_a = np.array(
[[False, False, False],
[True, True, True],
[True, True, True],
[False, False, False]]
)

and another array that looks like this:和另一个看起来像这样的数组:

arr_b = np.array(
[[100, 100, 100],
[200, 200, 200]]
)

I am looking for a function that I can call like this: np.boolean_combine(arr_a, arr_b) , to return an array that will replace the 1's in arr_a with the values from arr_b, for an end result that looks like this:我正在寻找一个可以这样调用的函数: np.boolean_combine(arr_a, arr_b) ,返回一个数组,该数组将用 arr_b 中的值替换 arr_a 中的 1,最终结果如下所示:

np.array(
[[0, 0, 0]
[100, 100, 100],
[200, 200, 200],
[0, 0, 0]]
)

Is there such a function?有这样的功能吗?

You can create a new array of the same dtype as arra_b , take a slice view using arr_a an assign the values from arra_b :可以创建相同的新数组dtype作为arra_b ,使用取切片视图arr_a一个分配从所述值arra_b

out = arr_a.astype(arra_b.dtype)
out[arr_a] = arra_b.ravel()

array([[  0,   0,   0],
       [100, 100, 100],
       [200, 200, 200],
       [  0,   0,   0]])

If your arr_a is made of 1's and 0's:如果您的 arr_a 由 1 和 0 组成:

import numpy as np 
arr_a = np.array(
[[0, 0, 0],
[1, 1, 1],
[1, 1, 1],
[0, 0, 0]])
arra_b = np.array(

[[100, 100, 100],

[200, 200, 200]])


arr_a[np.where(arr_a)]  = arra_b.reshape(arr_a[np.where(arr_a)].shape)

This works, assuming that the shapes are a match这有效,假设形状匹配

You can use zip() .您可以使用zip() Supposing that arr_a and arr_b are (obviously, from your problem) of the same dimension:假设 arr_a 和 arr_b 是(显然,从你的问题)相同的维度:

def boolean_combine(arr_a, arr_b) -> np.array:
  combined = []
  for row_a, row_b in zip(arr_a, arr_b):
    row_combined = []
    for a, b in zip(row_a, row_b):
      if a == 'True':
        row_combined.append(b)
      else:
        row_combined.append(a)
    combined.append(np.asarray(row_combined))
  return np.asarray(combined)

Then, you can call this function in your main just by typing combined = boolean_combine(arr_a, arr_b)然后,您可以通过键入combined = boolean_combine(arr_a, arr_b)在主程序中调用此函数

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

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