Python 在 Numpy 中,如何压缩两个二维数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17960441/
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 09:36:43  来源:igfitidea点击:

in Numpy, how to zip two 2-D arrays?

pythonarraysnumpyzip

提问by LWZ

For example I have 2 arrays

例如我有 2 个数组

a = array([[0, 1, 2, 3],
           [4, 5, 6, 7]])
b = array([[0, 1, 2, 3],
           [4, 5, 6, 7]])

How can I zipaand bso I get

我怎样才能zipab我得到

c = array([[(0,0), (1,1), (2,2), (3,3)],
           [(4,4), (5,5), (6,6), (7,7)]])

?

?

采纳答案by Daniel

You can use dstack:

您可以使用dstack

>>> np.dstack((a,b))
array([[[0, 0],
        [1, 1],
        [2, 2],
        [3, 3]],

       [[4, 4],
        [5, 5],
        [6, 6],
        [7, 7]]])

If you must have tuples:

如果你必须有元组:

>>> np.array(zip(a.ravel(),b.ravel()), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
       [(4, 4), (5, 5), (6, 6), (7, 7)]],
      dtype=[('f0', '<i4'), ('f1', '<i4')])


For Python 3+ you need to expand the zipiterator object. Please note that this is horribly inefficient:

对于 Python 3+,您需要扩展zip迭代器对象。请注意,这是非常低效的:

>>> np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
array([[(0, 0), (1, 1), (2, 2), (3, 3)],
       [(4, 4), (5, 5), (6, 6), (7, 7)]],
      dtype=[('f0', '<i4'), ('f1', '<i4')])

回答by Aert

np.array([zip(x,y) for x,y in zip(a,b)])