[英]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.