我想合并三个 numpy 数组,例如:
a = np.array([[0,0,1],[0,1,0],[1,0,0]])
b = np.array([[1,0,0],[0,1,0],[0,0,1]])
c = np.array([[0,1,0],[0,2,0],[0,1,0]])
a = array([[0, 0, 1],
[0, 1, 0],
[1, 0, 0]])
b = array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
c = array([[0, 1, 0],
[0, 2, 0],
[0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
期望的结果是覆盖它们,但在多个元素不为 0 的情况下保持最大值,例如在中间。
array([[1, 1, 1],
[0, 2, 0],
[1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
我通过迭代具有多个 if 条件的所有元素来解决这个问题。有没有更紧凑、更漂亮的方法来做到这一点?
NumPynp.ufunc.reduce允许沿给定轴累积应用函数。我们可以连接数组并减少numpy.maximum以保持累积的元素最大值:
np.maximum.reduce([a,b,c])
array([[1, 1, 1],
[0, 2, 0],
[1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用 Numpy np.dstack方法在额外维度中将数组堆叠在一起
并提取特定于添加维度的最大值
# Stacking arrays together
d = np.dstack([a,b,c])
d.max(axis=2)
Run Code Online (Sandbox Code Playgroud)
出去:
array([[1, 1, 1],
[0, 2, 0],
[1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
222 次 |
| 最近记录: |