2015-12-08 41 views
0

我有問題要問這個矩陣:我怎樣才能獲得真正的矩陣

A=([[2, 3, 4, 2, 1, 3, 4, 1, 3, 2 ]]) 

我想從A如下得到另一個矩陣:

B=([[0, 1, 0, 0], 
[0, 0, 1, 0], 
[0, 0, 0, 1], 
[0, 1, 0, 0], 
[1, 0, 0, 0], 
[0, 0, 1, 0], 
[0, 1, 0, 1], 
[1, 0, 0, 0], 
[0, 0, 1, 0], 
[0, 1, 0, 0]]) 

Iwritten此:

import numpy as np 
n=np.matrix('[2, 3, 4, 2, 1, 3, 4, 1, 3, 2]') 
c=np.matrix('[0, 0, 0, 0]') 
d=np.zeros((1,4)) 
for i in np.nditer(n): 
    h=d.itemset((0,i-1),1) 
    print d 

但我得到錯誤的matris如下

[[ 0. 1. 0. 0.]] 
[[ 0. 1. 1. 0.]] 
[[ 0. 1. 1. 1.]] 
[[ 0. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 
[[ 1. 1. 1. 1.]] 

我怎樣才能獲得真正的(B)矩陣?

+1

行'[0,1,0,1]'對嗎? – DSM

+0

簡短回答:在'for'循環中放入'd = np.zeros((1,4))',所以1不會累加。但是,你仍然沒有創建一個矩陣,只是打印出它的行。看到各種答案。 – greggo

回答

0

簡單numpy的解決方案,可能環路可與更好的性能量化操作所取代。

您在測試用例中出現錯誤,第七行應該是[0, 0, 0, 1]而不是[0, 1, 0, 1]

import numpy as np 

n = np.matrix([2, 3, 4, 2, 1, 3, 4, 1, 3, 2]) 
expected = np.array([[0, 1, 0, 0], 
        [0, 0, 1, 0], 
        [0, 0, 0, 1], 
        [0, 1, 0, 0], 
        [1, 0, 0, 0], 
        [0, 0, 1, 0], 
        [0, 0, 0, 1], 
        [1, 0, 0, 0], 
        [0, 0, 1, 0], 
        [0, 1, 0, 0]]) 


def make_result(input_vector): 
    output = np.zeros((input_vector.shape[1], np.max(input_vector))) 
    for idx, value in enumerate(np.nditer(n)): 
     output[idx, value - 1] = 1 
    return output 


result = make_result(n) 
assert (expected == result).all() 
0

這會幫助你:

from pprint import pprint 

A=[[2, 3, 4, 2, 1, 3, 4, 1, 3, 2 ]] 
B = [[0]*4 for _ in range(len(A[0]))] 

for i,val1 in enumerate(B[:]): 
    B[i][A[0][i]-1]=1 

pprint(B) 

輸出:

[[0, 1, 0, 0], 
[0, 0, 1, 0], 
[0, 0, 0, 1], 
[0, 1, 0, 0], 
[1, 0, 0, 0], 
[0, 0, 1, 0], 
[0, 0, 0, 1], 
[1, 0, 0, 0], 
[0, 0, 1, 0], 
[0, 1, 0, 0]] 
+0

感謝您的有趣。它真的很有幫助,我一次又一次地感謝 – Kemal

+1

然而,這不是一個numpy矩陣。所以你失去了所有的性能好處。 – ferrix

0

如果列和行數很少,那麼按列排列可能會更快。

import numpy as np 
n=np.matrix('[2, 3, 4, 2, 1, 3, 4, 1, 3, 2]') 
d=np.zeros((n.shape[1],4),dtype=int) 
for j in range(4): 
    d[:,j] = n==j+1 # True->1, False ->0 
print d 

[[0 1 0 0] 
[0 0 1 0] 
[0 0 0 1] 
[0 1 0 0] 
[1 0 0 0] 
[0 0 1 0] 
[0 0 0 1] 
[1 0 0 0] 
[0 0 1 0] 
[0 1 0 0]]