python - Numpy 通过交错连接数组

标签 python arrays numpy

我有 4 个数组,我想将它们连接成一个交错的数组。我该怎么做?

>>> import numpy as np
>>> a = np.tile(0,(5,2))
>>> b = np.tile(1,(5,2))
>>> c = np.tile(2,(5,2))
>>> d = np.tile(3,(5,2))
>>> e = np.concatenate((a,b,c,d),axis=1)
>>> e
    array([[0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3],
           [0, 0, 1, 1, 2, 2, 3, 3]])

这仅给出串联。

但是,我想要的输出是:

>>> desired_output
    array([[0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3],
           [0, 1, 2, 3, 0, 1, 2, 3]])

我的意思是我知道我可以使用以下方法从 e 中选择交错列:

>>> f = e[:, ::2]
>>> array([[0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3],
           [0, 1, 2, 3]])

但是如何制作一个大数组呢?

最佳答案

使用np.dstacknp.stack沿着最后一个轴堆叠,得到一个 3D 数组,然后重新整形回 2D -

np.dstack([a,b,c,d]).reshape(a.shape[0],-1)
np.stack([a,b,c,d],axis=2).reshape(a.shape[0],-1)

关于python - Numpy 通过交错连接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47430784/

相关文章:

python - 为什么 seek 在 python 中返回 None?

python - 如何修复Python中的 "String reversing"代码?

java - 创建一个新数组,其中包含目标值每次出现的索引

python - 在python中合并多个表后更改重复的列名

python - 如何对 Google Cloud NDB 代码进行单元测试?

python - kivy:为什么我不能改变矩形的颜色?

arrays - 尝试在数组中生成一定数量的随机放置的数字

c++ - char 数组的 strlen 大于其大小。如何避免?

python - 将 Python 序列(时间序列/数组)拆分为重叠的子序列

python - 在 tensorflow 中连接两个 RNN 状态