展平包含具有不同形状的numpy数组的列表

2024-09-22 14:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找到一种解决方案,用于展平以下numpy阵列列表:

a = np.arange(9).reshape(3,3)
b = np.arange(25).reshape(5,5)
c = np.arange(4).reshape(2,2)
myarrs = [a,b,c]

d = np.arange(5*5*5).reshape(5,5,5)
myarrs2 = [a,b,c,d]

对于我的myarrs,我目前正在使用:

res = np.hstack([np.hstack(i) for i in myarrs])

但我想知道是否有其他内置方法来执行此任务,特别是在具有不同形状的数组的情况下。 我看到了其他问题:Flattening a list of NumPy arrays?但它们通常指的是具有相同形状的数组


Tags: innumpy列表fornpres数组解决方案
2条回答

您可以尝试以下方法:

np.concatenate([x.ravel() for x in myarrs])

这应该比您的方法更快:

a = np.arange(9).reshape(3,3)
b = np.arange(25).reshape(5,5)
c = np.arange(4).reshape(2,2)
myarrs = [a,b,c]


res = np.concatenate([x.ravel() for x in myarrs])
print(res)
# [ 0  1  2  3  4  5  6  7  8  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24  0  1  2  3]


%timeit np.concatenate([x.ravel() for x in myarrs])
# 100000 loops, best of 3: 2.47 µs per loop
%timeit np.concatenate(list(map(lambda x: x.ravel(), myarrs)))
# 100000 loops, best of 3: 2.85 µs per loop
%timeit np.concatenate([x.flatten() for x in myarrs])
# 100000 loops, best of 3: 3.69 µs per loop
%timeit np.hstack([x.ravel() for x in myarrs])
# 100000 loops, best of 3: 5.69 µs per loop
%timeit np.hstack([np.hstack(i) for i in myarrs])
# 10000 loops, best of 3: 29.1 µs per loop

我知道您正在寻找numpy唯一的解决方案。但是,如果允许,还有一种可能性是将more_itertools^{}^{}^{}一起使用:

>>> import more_itertools
>>> list(more_itertools.flatten(([x.reshape(-1) for x in myarrs])))

比较:

原始解决方案

%timeit -n 100000 np.hstack([np.hstack(i) for i in myarrs])
> 31.6 µs ± 1.16 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

来自norok2的解决方案(最快)

%timeit -n 100000 np.concatenate([x.ravel() for x in myarrs])
> 2.62 µs ± 54.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

含有more_itertools+reshape(-1)

%timeit -n 100000 list(more_itertools.flatten(([x.reshape(-1) for x in myarrs])))
> 9.32 µs ± 255 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

more_itertools+ravel()

%timeit -n 100000 list(more_itertools.flatten(([x.ravel() for x in myarrs])))
> 7.33 µs ± 235 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

more_itertools+flatten()

%timeit list(more_itertools.flatten(([x.flatten() for x in myarrs])))
> 8.3 µs ± 65.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

相关问题 更多 >