Wie verwende ich einen 2-d boolean Array aus einem 1-d-Array auszuwählen auf einer pro-Zeile-Basis in numpy?

StackOverflow https://stackoverflow.com/questions/442218

  •  22-07-2019
  •  | 
  •  

Frage

Lassen Sie mich erläutern diese Frage mit einem Beispiel:

import numpy

matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant
base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above

result = numpy.array([ base[line] for line in matrix ])

result hält nun das gewünschte Ergebnis, aber ich bin sicher, es ist eine numpy-spezifische Methode, dies zu tun, die die explizite Iteration vermeidet. Was ist das?

War es hilfreich?

Lösung

Wenn ich Ihre Frage richtig verstanden habe, können Sie einfach Matrixmultiplikation verwenden:

result = numpy.dot(matrix, base)

Wenn das Ergebnis muß die gleiche Form hat, wie in Ihrem Beispiel nur eine reshape hinzufügen:

result = numpy.dot(matrix, base).reshape((5,1))

Wenn die Matrix symmetrisch ist nicht über die Reihenfolge, in Punkt vorsichtig sein.

Andere Tipps

Hier ist eine andere hässliche Art und Weise tun:

n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))

Mein Versuch:

numpy.sum(matrix * base, axis=1)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top