2011-03-27 7 views
0

다음 코드로 보간하려고합니다.파이썬 numpy 캐스트 문제

 self.indeces = np.arange(tmp_idx[len(tmp_idx) -1]) 
    self.samples = np.interp(self.indeces, tmp_idx, tmp_s) 

여기서 tmp_idx 및 tmp_s는 numpy 배열입니다. 다음 오류가 나타납니다.

array cannot be safely cast to required type

이 문제를 해결하는 방법을 알고 있습니까?

업데이트 :

 class myClass 
    def myfunction(self, in_array, in_indeces = None): 
     if(in_indeces is None): 
      self.indeces = np.arange(len(in_array)) 
     else: 
      self.indeces = in_indeces  
     # clean data 
     tmp_s = np.array; tmp_idx = np.array; 
     for i in range(len(in_indeces)): 
      if(math.isnan(in_array[i]) == False and in_array[i] != float('Inf')): 
       tmp_s = np.append(tmp_s, in_array[i]) 
       tmp_idx = np.append(tmp_idx, in_indeces[i]) 
     self.indeces = np.arange(tmp_idx[len(tmp_idx) -1]) 
     self.samples = np.interp(self.indeces, tmp_idx, tmp_s) 
+0

저에게 맞습니다. 'tmp_idx'와'tmp_s'의 타입은 무엇입니까? 오류를 출력하는보다 완전한 예제를 만들 수 있습니까? – tkerwin

+0

'self.indeces.dtype','tmp_idx.dtype' 및'tmp_s.dtype'을 보여주십시오. – unutbu

+0

그들은 int64 객체 객체입니다. – Bob

답변

2

하나는 당신이 다음 줄이있을 때 : 당신은 내장 함수 np.array에 tmp_stmp_idx을 설정하는

tmp_s = np.array; tmp_idx = np.array; 

. 그런 다음 추가 할 때 객체 유형 배열이 있습니다. np.interp은 처리 방법을 모릅니다. 아마도 길이가 0 인 빈 배열을 만들었다 고 생각했을 것입니다.하지만 numpy 나 python의 작동 방식이 아닙니다. 다음 대신 같은

시도 뭔가 :

class myClass 
    def myfunction(self, in_array, in_indeces = None): 
     if(in_indeces is None): 
      self.indeces = np.arange(len(in_array)) 
      # NOTE: Use in_array.size or in_array.shape[0], etc instead of len() 
     else: 
      self.indeces = in_indeces  
     # clean data 
     # set ii to the indices of in_array that are neither nan or inf 
     ii = ~np.isnan(in_array) & ~np.isinf(in_array) 
     # assuming in_indeces and in_array are the same shape 
     tmp_s = in_array[ii] 
     tmp_idx = in_indeces[ii] 
     self.indeces = np.arange(tmp_idx.size) 
     self.samples = np.interp(self.indeces, tmp_idx, tmp_s) 

나는 당신의 입력 또는 원하는 출력을 알 수 없기 때문에이 완벽하게 작동하지만, 이것은 당신이 시작하는 것을 보장. 참고로 numpy에서는 배열 전체에 대해 원하는 작업을 수행하는 메서드가 있으면 일반적으로 배열 요소를 반복하고 한 번에 하나씩 작업하지 않는 것이 좋습니다. 내장 된 numpy 메서드 사용은 항상 훨씬 빠릅니다. 확실히 numpy 문서를 통해 어떤 방법을 사용할 수 있는지 확인하십시오. 일반적인 파이썬리스트를 다루는 것과 같은 방법으로 numpy 배열을 처리하면 안된다.

+0

위의 코드를 업데이트하려고합니다 ... 작동하는 것처럼 보입니다 ... numpy 배열을 특정 데이터 (float 또는 double)라고 할 수 있습니까? – Bob

+0

@Banana, array.astype (type)은 배열의 변환 된 복사본을 반환합니다. 일반적으로 어레이를 만들 때 올바른 유형인지 확인하는 것이 가장 좋습니다. –