简体   繁体   English

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

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

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 zip a and b so I get我怎样才能zip ab所以我得到

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

? ?

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 zip iterator object.对于 Python 3+,您需要展开zip迭代器对象。 Please note that this is horribly inefficient:请注意,这是非常低效的:

>>> 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')])
np.array([zip(x,y) for x,y in zip(a,b)])

您还可以指定转置索引:

c = np.array([a,b]).transpose(1,2,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM