2016-01-04 135 views
0

加入兩個python數組我在Python中遇到了問題。我從字典條目創建兩個numpy數組。我想加入這兩個numpy的陣列以特定的方式是這樣的:通過索引

# create array with classes 
probVec = filePickle['classID'] 
a = np.empty([0, 1]) 

for x in np.nditer(probVec): 
    a = np.append(a,x) 

timeVec = filePickle['start'] 
timeVec = np.asarray(timeVec) 
b = np.empty([0, 1]) 

for x in np.nditer(timeVec): 
    b = np.append(b,x) 

# create input-vectors for clustering 
c = np.vstack((b,a)).transpose() 

現在,如果我想加入他們在一個更具體的方式,喜歡拍照的陣列「probVec」一起加入他們只有特定項目的數組「timeVec」像這樣的對應條目:

for x in np.nditer(probVec): 
    if x == 3.0: 
     a = np.append(a,x) 

for x in np.nditer(timeVec): 
    b = append with x values that have the same indices as the ones appended in the first loop 

因爲兩個陣列含有對應於各其它數值它們具有相同的長度。所以我的目標是這樣的:

probVec = [2.0, 1.0, 3.0, 3.0, 4.0, 3.0...] 

timeVec = [t1, t2, t3, t4, t5, t6...] 

c = [[3.0 t3] 
    [3.0 t4] 
    [3.0 t6] 
     . 
     . 
     . 
    ] 

我只是不知道什麼是要認識到的最好方式。

回答

0

在數組上使用比較運算符(如a == 3.0),可以得到一個布爾數組,用於索引,選擇條件爲true的行。

In [87]: a = np.random.randint(low=1, high=4, size=10) # example data 

In [88]: a 
Out[88]: array([3, 1, 3, 1, 1, 3, 2, 2, 2, 2]) 

In [89]: b = np.arange(10) 

In [90]: c = np.column_stack((a, b)) 

In [91]: c[a == 3] 
Out[91]: 
array([[3, 0], 
     [3, 2], 
     [3, 5]]) 
+0

完全沒有把戲。對不起,遲到接受! – Grmrk