2 回答

TA貢獻1789條經驗 獲得超10個贊
您可以通過以矢量化方式用零填充它們來將可迭代對象的初始數組轉換為 ndarray:
import numpy as np
a = np.array([[1, 2, 3, 4],
[2, 3, 4],
[4, 5, 6]])
max_len = len(max(a, key = lambda x: len(x))) # max length of iterable-objects contained in array
cust_func = np.vectorize(pyfunc=lambda x: np.pad(array=x,
pad_width=(0,max_len),
mode='constant',
constant_values=(0,0))[:max_len], otypes=[list])
a_pad = np.stack(cust_func(a))
輸出:
array([[1, 2, 3, 4],
[2, 3, 4, 0],
[4, 5, 6, 0]])

TA貢獻1842條經驗 獲得超13個贊
這取決于。您之前知道向量的大小還是要添加到列表中?
參見例如http://stackoverflow.com/a/58085045/7919597
例如,您可以填充數組
import numpy as np
a1 = [1, 2, 3, 4]
a2 = [2, 3, 4, np.nan] # pad with nan
a3 = [4, 5, 6, np.nan] # pad with nan
b = np.stack([a1, a2, a3], axis=0)
print(b)
# you can apply the normal numpy operations on
# arrays with nan, they usually just result in a nan
# in a resulting array
c = np.diff(b, axis=-1)
print(c)
之后,您可以在列上的每一行上應用一個移動窗口。
看看https://stackoverflow.com/a/22621523/7919597,它只有 1d,但可以讓您了解它是如何工作的。
可以通過 scipy.signal.convolve2d 使用只有一行作為內核的二維數組(形狀例如 (1, 3)),并使用上面的想法。這是獲得“逐行一維卷積”的解決方法:
from scipy import signal
krnl = np.array([[0, 1, 0]])
d = signal.convolve2d(c, krnl, mode='same')
print(d)
添加回答
舉報