2D 부울 배열을 사용하여 Numpy에서 1D 배열에서 선택하는 방법은 무엇입니까?

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

  •  22-07-2019
  •  | 
  •  

문제

이 질문을 예를 들어 설명하겠습니다.

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 이제 원하는 결과를 보유하고 있지만 명시 적 반복을 피하는이 작업을 수행하는 Numpy 특정 방법이 있다고 확신합니다. 무엇입니까?

도움이 되었습니까?

해결책

질문을 올바르게 이해하면 매트릭스 곱셈을 사용할 수 있습니다.

result = numpy.dot(matrix, base)

결과가 예제와 동일한 모양을 가져야하는 경우 다시 한 가지를 추가하십시오.

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

행렬이 대칭이 아닌 경우 DOT의 순서에주의하십시오.

다른 팁

다음은 또 다른 추악한 방법입니다.

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

내 시도 :

numpy.sum(matrix * base, axis=1)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top