[英]adding arrays of different dimension in all cases python
x = np.array([[1],[1],[3]])
y = np.array([[1],[2]])
x+y
我有幾個 arrays 我想加在一起,它們的結構像上面的例子。 我想將這些 arrays 加在一起,在維度不匹配的地方我想將 0 添加到該值。 即結果應該是
array([[2],
[3],
[3]])
我不知道“x”或“y”中哪個維度更高。 有沒有好的方法來處理這個問題? 我嘗試將 arrays 的大小調整為兩者之間的最大值,但沒有成功
另一種可能的解決方案,它使用numpy.pad
:
max_shape = np.maximum(x.shape[0], y.shape[0])
x = np.pad(x, ((0, max_shape - x.shape[0]), (0, 0)), mode='constant')
y = np.pad(y, ((0, max_shape - y.shape[0]), (0, 0)), mode='constant')
x + y
Output:
array([[2],
[3],
[3]])
只需創建另一個與較長數組大小相同的數組,並用零填充短數組的空值,然后將其與較長數組相加。
import numpy as np
def sum_padded(x,y):
if len(x) > len(y):
new_arr = np.zeros_like(x)
new_arr[:len(y)] = y
return x + new_arr
elif len(x) < len(y):
new_arr = np.zeros_like(y)
new_arr[:len(x)] = x
return y + new_arr
else:
return x + y
x = np.array([[1],[1],[3]])
y = np.array([[1],[2]])
res = sum_padded(x,y)
print(res)
[[2]
[3]
[3]]
請注意,這是假設它們具有不同的第一維,如果存在比第一維更多的差異,那么它會變得稍微復雜一些,因為您必須創建兩個新的 arrays,其形狀是兩者的最大值所有維度。
這是一個可能的解決方案:
all_arrays = [x, y]
max_len = max([len(arr) for arr in all_arrays])
sum_arr = np.zeros(max_len)
for arr in all_arrays:
add_these_zeros = max_len - len(arr)
sum_arr = sum_arr + np.concatenate([arr.flatten(), np.zeros(add_these_zeros)])
print(np.reshape(sum_arr, (-1, 1))) # reshape 1D to 2D
all_arrays
sum_arr
OUTPUT:
array([[2.],
[3.],
[3.]])
跟蹤各種維度似乎是症結所在。 在這里,我使用 ravel / slice / reshape 來靈活處理。
def make_uniform(x, y):
large = x if x.shape > y.shape else y
# We return x with large.shape, optionally appending zeros.
n = np.product(large.shape)
return (
np.concatenate(x, np.zeros_like(large))
.ravel()[:n]
.reshape(large.shape)
)
x, y = (make_uniform(x, y),
make_uniform(y, x))
x + y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.