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条经验 获得超12个赞
这取决于。您之前知道向量的大小还是要添加到列表中?
参见例如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)
添加回答
举报