Python 连接作为列表元素的 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28125265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:45:52  来源:igfitidea点击:

concatenate numpy arrays which are elements of a list

pythonarrayslistnumpy

提问by TNM

I have a list containing numpy arrays something like L=[a,b,c] where a, b and c are numpy arrays with sizes N_a in T, N_b in T and N_c in T.
I want to row-wise concatenate a, b and c and get a numpy array with shape (N_a+N_b+N_c, T). Clearly one solution is run a for loop and use numpy.concatenate, but is there any pythonic way to do this?

我有一个包含类似 L=[a,b,c] 的 numpy 数组的列表,其中 a、b 和 c 是大小为 N_a 的 numpy 数组,T 中的大小为 N_a,T 中的 N_b 和 T 中的 N_c。
我想逐行连接 a, b 和 c 并得到一个形状为 (N_a+N_b+N_c, T) 的 numpy 数组。显然,一种解决方案是运行 for 循环并使用 numpy.concatenate,但是有没有 Pythonic 方法可以做到这一点?

Thanks

谢谢

采纳答案by shx2

Use numpy.vstack.

使用numpy.vstack.

L = (a,b,c)
arr = np.vstack(L)

回答by hpaulj

help('concatenate'has this signature:

help('concatenate'有这个签名:

concatenate(...)
    concatenate((a1, a2, ...), axis=0)

    Join a sequence of arrays together.

(a1, a2, ...)looks like your list, doesn't it? And the default axis is the one you want to join. So lets try it:

(a1, a2, ...)看起来像你的清单,不是吗?默认轴是您要加入的轴。所以让我们尝试一下:

In [149]: L = [np.ones((3,2)), np.zeros((2,2)), np.ones((4,2))]

In [150]: np.concatenate(L)
Out[150]: 
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 0.,  0.],
       [ 0.,  0.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])

vstackalso does this, but look at its code:

vstack也这样做,但看看它的代码:

def vstack(tup):
    return np.concatenate([atleast_2d(_m) for _m in tup], 0)

All it does extra is make sure that the component arrays have 2 dimensions, which yours do.

它所做的额外工作是确保组件数组具有 2 维,而您的数组是这样的。