簡體   English   中英

在所有情況下添加不同維度的 arrays python

[英]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
  • 首先將所有 arrays 放入all_arrays
  • 計算最長數組的長度
  • 創建一個數組,其中的零個數與上一步中計算的最大長度一樣多。
  • 遍歷 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM