2017-12-12 11 views
0

64 비트 Win1o에서 Python 3을 사용하고 있습니다.np.NaN을 사용하는 중 오류가 벡터화 함수 인 경우

def skudiscounT(t): 
    s = t.find("ITEMADJ") 
    if s >= 0: 
     t = t[s + 8:] 
     if t.find("-") == 2: 
      return t 
    else: 
     return np.nan # if change to "" it will work fine! 

내가 np.Vectorize에서이 기능을 사용하려고 다음과 같은 오류가있어 :

Traceback (most recent call last): 
File "C:/Users/lz09/Desktop/P3/SODetails_Clean_V1.py", line 45, in <module> 
SO["SKUDiscount"] = np.vectorize(skudiscounT)(SO['Description']) 
File "C:\PD\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 2739, in __call__ 
return self._vectorize_call(func=func, args=vargs) 
File "C:\PD\Anaconda3\lib\site-packages\numpy\lib\function_base.py", line 2818, in _vectorize_call 
res = array(outputs, copy=False, subok=True, dtype=otypes[0]) 
ValueError: could not convert string to float: '23-126-408' 

내가 마지막 줄을 교체 [리턴 np.nan을 나는 다음과 같은 간단한 기능에 문제가 있었다 ]에서 [return '']로 잘 돌아갔습니다. 왜 이것이 사실인지 누구나 알고 있습니까? 감사!

+0

'vectorize'는 어떤 종류의 배열이 반환되어야 하는지를 결정하기위한 테스트 계산을합니다. 귀하의 함수는 때때로 문자열을 반환하고 다른 때에는 부동 (''nan') 한 것처럼 보입니다. 그걸 망칠 수 있습니다. 함수가 일관성있는 dtype을 반환하는지 확인하는 것이 좋습니다. 또한'otypes' 매개 변수를 살펴보십시오. 문서의 두 번째 단락을 읽으십시오. – hpaulj

답변

0

otypes없이 반환 배열의 DTYPE은 1 심 결과에 의해 결정된다 : 나는 문자열을 반환 인수를 찾기 위해 노력하고있어

In [232]: f = np.vectorize(skudiscounT) 
In [234]: f(['abc']) 
Out[234]: array([ nan]) 
In [235]: _.dtype 
Out[235]: dtype('float64') 

. 귀하의 기능도 None을 (를) 반환 할 수있는 것 같습니다.

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

otypes으로 : 워드 프로세서

In [246]: f = np.vectorize(skudiscounT, otypes=[object]) 
In [247]: f(['abc', '23-126ITEMADJ408']) 
Out[247]: array([nan, None], dtype=object) 
In [248]: f = np.vectorize(skudiscounT, otypes=['U10']) 
In [249]: f(['abc', '23-126ITEMADJ408']) 
Out[249]: 
array(['nan', 'None'], 
     dtype='<U4') 

그러나 일반적인 object DTYPE를 반환, 나는 약간 빠른 사용하십시오 :

In [250]: g = np.frompyfunc(skudiscounT, 1,1) 
In [251]: g(['abc', '23-126ITEMADJ408']) 
Out[251]: array([nan, None], dtype=object) 

을 그래서 원하는 종류의 배열을 원하십니까? 보유 할 수있는 floatnp.nan, string? 또는 '무엇이든'저장할 수있는 object

+0

감사합니다. @hapulj. 개체 유형이 필요합니다. otypes = [object]를 추가 한 후 효과가있었습니다! – LarryZ