G M*_*G M 4 python arrays numpy
我试图找到一个解决方案来展平以下 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]
Run Code Online (Sandbox Code Playgroud)
对于我myarrs目前正在使用的:
res = np.hstack([np.hstack(i) for i in myarrs])
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有任何其他内置方法可以执行此任务,特别是在具有不同形状的数组的情况下。我看到了其他问题: Flattening a list of NumPy arrays? 但它们通常指的是具有相同形状的数组。
你可以尝试这样的事情:
np.concatenate([x.ravel() for x in myarrs])
Run Code Online (Sandbox Code Playgroud)
这应该比您的方法更快:
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
Run Code Online (Sandbox Code Playgroud)