python 中有没有一种方法可以合并两个数组 (1d/2d/3d) 并替换特定元素

is there a way in python that can I merge two arrays (1d/2d/3d) and replacing specific elements

简单案例- 我有两个数组: x1 = np.arange(1,10)x2 = np.array([0,0,4,0,0,5,0,0,0])

我想合并或合并这两个数组,以便 x2 中的 0 将替换为 x1 中的值和 [=16 中的非零元素=] 仍然存在。 NumPy.union1d 好像是做这个联合的。但是我想要它sorted/ordered。

然后

实际案例- 然后我想在多维数组上执行此操作,例如:x.shape=(xx,yy,zz)。两个数组对象将具有相同的形状。 x.shape = y.shape

这可能吗?我应该尝试使用屏蔽数组 NumPy.ma 吗?

------------------------示例---------------- ------------

k_angle = khan(_angle)
e_angle = emss(_angle)

_angle.shape = (3647, 16)
e_angle.shape = (2394, 3647, 16)
k_angle.shape = (2394, 3647, 16)

_angle 包含一个值列表 0 - 180 度,如果角度 < 5 它应该只使用一个函数 khan 其他任何东西都是 emss 函数。 对于 khan,任何大于 5 的值都会变为 0emss 适用于所有值。

尝试 1: 我尝试拆分角度值,但重新组合它们很棘手

khan = bm.Khans_beam_model(freq=f, theta=None)
emss = bm.emss_beam_model(f=f)

test = np.array([[0,1,2], [3,4,5], [6,7,8], [9,10,11]])

gt_idx = test > 5
le_idx = test <= 5
# then update the array
test[gt_idx] = khan(test[gt_idx])
test[le_idx] = emss(test[le_idx])

但这会出错TypeError: NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions

khanemss 是 `lambda' 函数

所以我认为执行khanemss然后事后合并会更容易。

我应用了上面的简单案例来帮助解决这个问题。

只要x1x2的形状相同,np.where(boolean_mask, value_if_true, value_otherwise)的功能就足够了。

在这里,您可以使用 np.where(x2, x2, x1),其中条件只是 x2,这意味着真值(非零)将被保留,假值将被相应的值替换x1。一般来说,任何布尔掩码都可以作为条件,最好在这里明确:np.where(x2 == 0, x1, x2).

1D

In [1]: import numpy as np

In [2]: x1 = np.arange(1, 10)

In [3]: x2 = np.array([0,0,4,0,0,5,0,0,0])

In [4]: np.where(x2 == 0, x1, x2)
Out[4]: array([1, 2, 4, 4, 5, 5, 7, 8, 9])

二维

In [5]: x1 = x1.reshape(3, 3)

In [6]: x2 = x2.reshape(3, 3)

In [7]: x1
Out[7]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [8]: x2
Out[8]:
array([[0, 0, 4],
       [0, 0, 5],
       [0, 0, 0]])

In [9]: np.where(x2 == 0, x1, x2)
Out[9]:
array([[1, 2, 4],
       [4, 5, 5],
       [7, 8, 9]])

3D

In [10]: x1 = np.random.randint(1, 9, (2, 3, 3))

In [11]: x2 = np.random.choice((0, 0, 0, 0, 0, 0, 0, 0, 99), (2, 3, 3))

In [12]: x1
Out[12]:
array([[[3, 7, 4],
        [1, 4, 3],
        [7, 4, 3]],

       [[5, 7, 1],
        [5, 7, 6],
        [1, 8, 8]]])

In [13]: x2
Out[13]:
array([[[ 0, 99, 99],
        [ 0, 99,  0],
        [ 0, 99,  0]],

       [[99,  0,  0],
        [ 0,  0, 99],
        [ 0, 99,  0]]])

In [14]: np.where(x2 == 0, x1, x2)
Out[14]:
array([[[ 3, 99, 99],
        [ 1, 99,  3],
        [ 7, 99,  3]],

       [[99,  7,  1],
        [ 5,  7, 99],
        [ 1, 99,  8]]])