Seite 1 von 1

Matrixspalten umstellen

Verfasst: Montag 9. Mai 2016, 19:01
von Goswin
Wenn ich (auf elegante Art) die Spalten einer Matrix umstellen möchte, kann ich das so wie folgt NICHT machen:

Code: Alles auswählen

import scipy as sc
mat = sc.matrix([[1,2,3,], [4,5,6], [7,8,9]])
#
(mat[:,0], mat[:,1]) = (mat[:,1], mat[:,0])  #FALSCH
print(mat)
Das beste was mir bisher dazu einfällt ist

Code: Alles auswählen

import scipy as sc
mat = sc.matrix([[1,2,3,], [4,5,6], [7,8,9]])
#
lst = [zeile for zeile in sc.array(mat.T)]
(lst[0], lst[1]) = (lst[1], lst[0])
mat = sc.matrix(lst).T
print(mat)
aber das ist wohl nicht zu empfehlen, oder?

Re: Matrixspalten umstellen

Verfasst: Montag 9. Mai 2016, 19:14
von BlackJack
@Goswin: Das Slices soweit das möglich ist immer nur Views auf die Daten in dem Array sind, geht das nicht ganz so wie Du es versuchst hast. Du musst von mindestens einem View auf der rechten Seite der Zuweisung explizit eine Kopie machen:

Code: Alles auswählen

In [12]: mat = sc.array([[1,2,3,], [4,5,6], [7,8,9]])

In [13]: mat
Out[13]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [14]: mat[:, 0], mat[:, 1] = mat[:, 1], mat[:, 0].copy()

In [15]: mat
Out[15]: 
array([[2, 1, 3],
       [5, 4, 6],
       [8, 7, 9]])

Re: Matrixspalten umstellen

Verfasst: Montag 9. Mai 2016, 19:30
von MagBen
Probier das mal:

Code: Alles auswählen

import scipy as sc
mat = sc.matrix([[1,2,3,], [4,5,6], [7,8,9]])
mat[:,[0,1]] = mat[:,[1,0]]
print(mat)

Re: Matrixspalten umstellen

Verfasst: Montag 9. Mai 2016, 19:48
von Goswin
Vielen Dank, es funktioniert beides! :D