gpt4 book ai didi

python - 如何交错 numpy.ndarrays?

转载 作者:太空狗 更新时间:2023-10-30 00:01:39 26 4
gpt4 key购买 nike

我目前正在寻找可以交错 2 个 numpy.ndarray 的方法。这样

>>> a = np.random.rand(5,5)
>>> print a
[[ 0.83367208 0.29507876 0.41849799 0.58342521 0.81810562]
[ 0.31363351 0.69468009 0.14960363 0.7685722 0.56240711]
[ 0.49368821 0.46409791 0.09042236 0.68706312 0.98430387]
[ 0.21816242 0.87907115 0.49534121 0.60453302 0.75152033]
[ 0.10510938 0.55387841 0.37992348 0.6754701 0.27095986]]
>>> b = np.random.rand(5,5)
>>> print b
[[ 0.52237011 0.75242666 0.39895415 0.66519185 0.87043142]
[ 0.08624797 0.66193953 0.80640822 0.95403594 0.33977566]
[ 0.13789573 0.84868366 0.09734757 0.06010175 0.48043968]
[ 0.28871551 0.62186888 0.44603741 0.3351644 0.6417847 ]
[ 0.85745394 0.93179792 0.62535765 0.96625077 0.86880908]]
>>>

打印 c 应该交错每一行两个矩阵

[ 0.83367208   0.52237011  0.29507876 0.75242666 0.41849799 0.39895415 0.58342521 0.66519185 0.81810562 0.87043142]

我总共有三个应该交错的,但我想一次做两个会更容易..

但我如何轻松地做到这一点..我阅读了一些使用数组的方法,但我不确定是否使用 ndarrays 来做到这一点?

最佳答案

np.dstack沿着第三轴堆叠那些并 reshape 回 2D -

np.dstack((a,b)).reshape(a.shape[0],-1)

对于三个数组或更多数组,只需将它们相加即可。因此,对于三个数组,使用:np.dstack((a,b,c)) 并用 c reshape 为第三个数组。

sample 运行-

In [99]: a
Out[99]:
array([[8, 4, 0, 5, 6],
[0, 2, 3, 0, 6],
[4, 4, 0, 6, 5],
[7, 5, 0, 7, 0],
[6, 7, 4, 7, 2]])

In [100]: b
Out[100]:
array([[3, 5, 8, 6, 5],
[5, 6, 8, 8, 4],
[8, 3, 3, 3, 5],
[2, 1, 1, 1, 3],
[5, 7, 7, 5, 7]])

In [101]: np.dstack((a,b)).reshape(a.shape[0],-1)
Out[101]:
array([[8, 3, 4, 5, 0, 8, 5, 6, 6, 5],
[0, 5, 2, 6, 3, 8, 0, 8, 6, 4],
[4, 8, 4, 3, 0, 3, 6, 3, 5, 5],
[7, 2, 5, 1, 0, 1, 7, 1, 0, 3],
[6, 5, 7, 7, 4, 7, 7, 5, 2, 7]])

关于python - 如何交错 numpy.ndarrays?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42162300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com