[英]Conditional Sum of 2D Numpy Arrays
我有4個(但實際上是任意數量的)2D數組,如下所示:
import numpy as np
c1 = np.ones((75, 100))
c2 = np.ones((75, 100))
c3 = np.ones((75, 100))
c4 = np.ones((75, 100))
c1[22:42, 5:35] = np.random.rand(20, 30) / 2
c2[25:45, 25:55] = np.random.rand(20, 30) / 2
c3[28:48, 45:75] = np.random.rand(20, 30) / 2
c4[31:51, 65:95] = np.random.rand(20, 30) / 2
我想做的是將數組的所有地方加起來,除了數組重疊的地方。 在有重疊的地方,該值應為左數組。 我的本能是使用np.where
,但是我想不到這樣做的聰明/巧妙的方法。
希望下面的圖片可以清楚地說明這一點
c_arrays = np.array([c1, c2, c3, c4])
result = c_arrays.sum(axis=0)
fig, ax = plt.subplots()
ax.imshow(result)
編輯 :我想出了一個糟糕的,遞歸的解決方案,至少顯示了我正在尋找的結果。 我希望有人可以提供一種更簡潔的方法,尤其是這種方法不是遞歸的
c_arrays_1 = []
for ci, cj in zip(c_arrays, c_arrays[1:]):
c = np.where(ci + cj < 1, ci, ci + cj - 1)
c_arrays_1.append(c)
c_arrays_2 = []
for ci, cj in zip(c_arrays_1, c_arrays_1[1:]):
c = np.where(ci + cj < 1, ci, ci + cj - 1)
c_arrays_2.append(c)
c_arrays_3 = []
for ci, cj in zip(c_arrays_2, c_arrays_2[1:]):
c = np.where(ci + cj < 1, ci, ci + cj - 1)
c_arrays_3.append(c)
fig, ax = plt.subplots()
ax.imshow(c_arrays_3[0])
我認為這是一種適合您要求的遞歸方法:
def condsum(*arrs, r = 1):
if len(arrs) == 1:
return arrs[0]
else:
a = condsum(*arrs[1:], r = r)
return np.where(a == r, arrs[0], a)
那你只需要做
plt.imshow(condsum(c1, c2, c3, c4))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.