2013-05-28 5 views
1

np.fromfunction을 사용하여 함수를 기반으로 특정 크기의 배열을 만듭니다. 그것은 다음과 같습니다함수를 사용하여 numpy 배열을 만드는 방법은 무엇입니까?

TypeError: only integer arrays with one element can be converted to an index 
+0

참고 용 : [numpy 소스보기] (https://github.com/numpy/numpy/blob/v1.7.0/numpy/core/numeric.py#L1611)'fromfunction'은'index'를 생성합니다. 배열에 저장하고이를 사용자 함수에 전달합니다. 그래서'i'와'j'는'int'가 아니라'array's입니다. – mg007

+0

@ mg007 나는이 함수가 이들을 언 박싱 할 것이라고 믿는다. – sdasdadas

+0

당신은이 비슷한 질문에서 그 일을 어떻게 수행하는지 볼 수 있습니다 : http://stackoverflow.com/questions/400739/what-does-mean-in-python – sdasdadas

답변

6

기능은 NumPy와 배열을 처리해야 :

import numpy as np 
test = [[1,0],[0,2]] 
f = lambda i, j: sum(test[i]) 
matrix = np.fromfunction(f, (len(test), len(test)), dtype=int) 

그러나, 나는 다음과 같은 오류가 발생합니다. 이 작업을 얻을 수있는 쉬운 방법은 다음과 같습니다

import numpy as np 
test = [[1,0],[0,2]] 
f = lambda i, j: sum(test[i]) 
matrix = np.fromfunction(np.vectorize(f), (len(test), len(test)), dtype=int) 

np.vectorize 올바르게 배열을 처리 할 F의 벡터화 버전을 반환합니다.

+0

당신은 제 영웅입니다! – sdasdadas

+0

'np.vectorize'를 통해 함수를 전달하는 것은 _the_ 트릭 문서가 지적하지 못했기 때문에, 정말 고마워요. – blue

관련 문제