【问题标题】:is there a way in python that can I merge two arrays (1d/2d/3d) and replacing specific elementspython中有没有一种方法可以合并两个数组(1d/2d/3d)并替换特定元素
【发布时间】:2021-11-26 02:33:31
【问题描述】:

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

我想合并或组合这两个数组,以便x2 中的0 将替换为x1 中的值,而x2 的非零元素仍然存在。 NumPy.union1d 似乎做了这个联合。但我不想对其进行排序/排序。

然后

实际情况- 然后我想在多维数组上执行此操作,例如: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 度的值列表,如果角度 khan 其他任何函数都是 emss 函数。 khan 的任何大于 5 的值都将变为 0。而emss 适用于所有值。

尝试 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 然后在事后合并会更容易。

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

【问题讨论】:

  • 您能否发布您的代码努力并提供一个具有实际和预期结果的最小可重现示例?
  • @marcelh 做一个可重现的例子有点挑战,但我会尝试重做我的问题

标签: python arrays numpy merge


【解决方案1】:

只要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]]])

【讨论】:

  • 感谢您为此以及使用 np.where 函数展示新技巧
  • 不客气,很高兴我能帮上忙。
猜你喜欢
  • 2016-01-04
  • 2014-10-13
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多