2017-03-25 105 views
2

我想「連接」兩個相同形狀的二維numpy數組來創建一個三維numpy數組。我可以使用循環輕鬆完成此操作,但我正在尋找更快的方法。這是玩具的例子。這兩個numpy陣列是:python:連接兩個二維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]]]) 

請讓我知道。

回答

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]]] 
+2

現在帶着幾分更多的靈活性,'np.stack((),軸= -1)'。 – hpaulj

+0

@hpaulj好戲!特別是對於這個問題,'np.stack((),axis = 2)'很清楚。但是,使用'axis = -1'適用於一般設置:) – kmario23

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