2017-04-22 249 views
2

我想用相同數量的參數合併兩個數組。合併兩個numpy數組

輸入:

first = [[650001.88, 300442.2, 18.73, 0.575, 650002.094, 300441.668, 18.775], 
     [650001.96, 300443.4, 18.7, 0.65, 650002.571, 300443.182, 18.745], 
     [650002.95, 300442.54, 18.82, 0.473, 650003.056, 300442.085, 18.745]] 

second = [[1], 
      [2], 
      [3]] 

我的預期輸出:

final = [[650001.88, 300442.2, 18.73, 0.575, 650002.094, 300441.668, 18.775, 1], 
      [650001.96, 300443.4, 18.7, 0.65, 650002.571, 300443.182, 18.745, 2], 
      [650002.95, 300442.54, 18.82, 0.473, 650003.056, 300442.085, 18.745, 3]] 

要做到這一點我創建簡單的循環:

for i in first: 
     for j in second: 
      final += np.append(j, i) 

我得到了我填,我失去了一些東西。首先,我的循環非常緩慢。其次我的數據是相當有超過2 mlns行循環。所以,我試圖找到例如更快的方法與此代碼:

final = [np.append(i, second[0]) for i in first] 

它的工作遠遠比以前更循環速度較快,但其追加第二陣列的只有第一個值。 你能幫我嗎?

回答

5

使用np.array然後np.concatenate

import numpy as np 

first = np.array([[650001.88, 300442.2, 18.73, 0.575, 
        650002.094, 300441.668, 18.775], 
        [650001.96, 300443.4, 18.7, 0.65, 
        650002.571, 300443.182, 18.745], 
        [650002.95, 300442.54, 18.82, 0.473, 
        650003.056, 300442.085, 18.745]]) 

second = np.array([[1], 
        [2], 
        [3]]) 

np.concatenate((first, second), axis=1) 

axis=1意味着我們要水平串聯。

這對我的作品

1

使用np.column_stack

import numpy as np 

first = [[650001.88, 300442.2, 18.73, 0.575, 650002.094, 300441.668, 18.775], 
     [650001.96, 300443.4, 18.7, 0.65, 650002.571, 300443.182, 18.745], 
     [650002.95, 300442.54, 18.82, 0.473, 650003.056, 300442.085, 18.745]] 

second = [[1], 
      [2], 
      [3]] 

np.column_stack([first, second]) 

如果你需要它作爲一個列表,使用方法tolist

np.column_stack([first, second]).tolist()