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

标签 python arrays numpy zip

例如我有 2 个数组

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

我怎样才能 zip ab 所以我得到

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

?

最佳答案

您可以使用 dstack :

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

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

如果你必须有元组:

>>> 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')])

对于 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')])

关于python - 在 Numpy 中,如何压缩两个二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17960441/

相关文章:

python - 在 python 中查找重叠或插入的行

列名中带有空格的python数据框查询

ios - swift3 append 函数在 firebase observeSingleEvent 内部不起作用

python - Numpy astype 四舍五入到错误的值

python - 监控 GET 请求 Python 的状态

python - 获取已排序 Numpy 数组的原始索引

arrays - 如何在 Julia 中对可变数量的列表进行笛卡尔积?

r - data.frame 具有包含数组的列

python - 在python中添加具有相同运算符的lambda函数

python - 分组依据 占总数的百分比