我想“加入”两个相同形状的二维numpy数组来创建一个维度numpy数组。我可以使用循环轻松完成此操作,但我正在寻找更快的方法。这是玩具的例子。两个numpy数组是:
data1 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
data2 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])*100
data1
> array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
data2
> array([[ 100, 200, 300, 400, 500],
[ 600, 700, 800, 900, 1000],
[1100, 1200, 1300, 1400, 1500]])
两者都有形状(3,5)。我想创建(3,5,2)形状numpy数组。那就是:
data3 = []
for irow in range(data1.shape[0]):
data3_temp = []
for icol in range(data1.shape[1]):
data3_temp.append([data1[irow,icol],
data2[irow,icol]])
data3.append(data3_temp)
data3 = np.array(data3)
data3.shape
> (3, 5, 2)
data3
>array([[[ 1, 100],
[ 2, 200],
[ 3, 300],
[ 4, 400],
[ 5, 500]],
[[ 6, 600],
[ 7, 700],
[ 8, 800],
[ 9, 900],
[ 10, 1000]],
[[ 11, 1100],
[ 12, 1200],
[ 13, 1300],
[ 14, 1400],
[ 15, 1500]]])
请告诉我。
答案 0 :(得分:2)
使用numpy.dstack
按顺序深度(沿第三轴)堆叠数组:https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.dstack.html
import numpy as np
data1 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
data2 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])*100
print np.dstack((data1,data2))
输出:
[[[ 1 100]
[ 2 200]
[ 3 300]
[ 4 400]
[ 5 500]]
[[ 6 600]
[ 7 700]
[ 8 800]
[ 9 900]
[ 10 1000]]
[[ 11 1100]
[ 12 1200]
[ 13 1300]
[ 14 1400]
[ 15 1500]]]
答案 1 :(得分:1)
一种方法:
data3= np.zeros([ data1.shape[0],data1.shape[1], 2])
data3[:,:,0],data3[:,:,1] = data1,data2
print data3.shape
print data3
结果
(3L, 5L, 2L)
>array([[[ 1, 100],
[ 2, 200],
[ 3, 300],
[ 4, 400],
[ 5, 500]],
[[ 6, 600],
[ 7, 700],
[ 8, 800],
[ 9, 900],
[ 10, 1000]],
[[ 11, 1100],
[ 12, 1200],
[ 13, 1300],
[ 14, 1400],
[ 15, 1500]]])
答案 2 :(得分:1)
或者您可以使用r_
连接符:
np.r_['2,3,0', data1, data2]
# array([[[ 1, 100],
[ 2, 200],
[ 3, 300],
[ 4, 400],
[ 5, 500]],
[[ 6, 600],
[ 7, 700],
[ 8, 800],
[ 9, 900],
[ 10, 1000]],
[[ 11, 1100],
[ 12, 1200],
[ 13, 1300],
[ 14, 1400],
[ 15, 1500]]])