2017-09-06 2 views
1

Ich habe ein ndarray wie folgt.Fügen Sie eine zusätzliche Spalte zu NDarray in Python

feature_matrix = [[0.1, 0.3], [0.7, 0.8], [0.8, 0.8]] 

Ich habe eine Position ndarray wie folgt.

position = [10, 20, 30] 

Jetzt möchte ich den Positionswert am Anfang der Feature-Matrix wie folgt hinzufügen.

[[10, 0.1, 0.3], [20, 0.7, 0.8], [30, 0.8, 0.8]] 

habe ich versucht, die Antworten in dieser: How to add an extra column to an numpy array

E.g., 

feature_matrix = np.concatenate((feature_matrix, position), axis=1) 

Allerdings bekomme ich den Fehler, dass zu sagen;

ValueError: all the input arrays must have same number of dimensions 

Bitte helfen Sie mir dieses Problem zu lösen.

+0

Verwenden Sie einfach 'np.column_stack'. – Divakar

+0

Haben Sie versucht, meine Antwort an Ihre vorherige Frage anzupassen? 'np.insert (feature_matrix, 0, [10,20,30], ax is = 1)'; https://stackoverflow.com/questions/46065339/how-to-insert-list-of-tarray-lists-to-a-newndarray-in-python – hpaulj

+0

Ja, ich bekomme SyntaxError: ungültiges Zeichen in Bezeichner. das kommt für den Achsenteil. –

Antwort

1

Das löste mein Problem. Ich habe np.column_stack benutzt.

feature_matrix = [[0.1, 0.3], [0.7, 0.8], [0.8, 0.8]] 
position = [10, 20, 30] 
feature_matrix = np.column_stack((position, feature_matrix)) 
0

Es ist die Form des position Array, das in Bezug auf die Form des feature_matrix falsch ist.

>>> feature_matrix 
array([[ 0.1, 0.3], 
     [ 0.7, 0.8], 
     [ 0.8, 0.8]]) 

>>> position 
array([10, 20, 30]) 

>>> position.reshape((3,1)) 
array([[10], 
     [20], 
     [30]]) 

Die Lösung ist (mit np.concatenate):

>>> np.concatenate((position.reshape((3,1)), feature_matrix), axis=1) 
array([[ 10. , 0.1, 0.3], 
     [ 20. , 0.7, 0.8], 
     [ 30. , 0.8, 0.8]]) 

Aber np.column_stack in Ihrem Fall klar ist großartig!

Verwandte Themen