2013-10-21 2 views
3

dtype = object로 numpy 배열을 취하고 배열의 모든 요소가 부동 소수점, 정수 또는 문자열인지 여부를 반환하는 함수 F를 작성해야합니다. 예 :numpy 배열의 모든 요소가 수레인지 신속하게 확인하려면 어떻게해야합니까?

F(np.array([1., 2.], dtype=object)) --> float 
F(np.array(['1.', '2.'], dtype=object)) --> string 
F(np.array([1, 2], dtype=object)) --> int 
F(np.array([1, 2.], dtype=object)) --> float 
F(np.array(['hello'], dtype=object)) --> string 

F(np.array([1, 'hello'], dtype=object)) --> ERROR 

아이디어를 효과적으로 만드는 방법은 무엇입니까? (== 내장 함수 NumPy와와)

덕분에 많은

+1

F (np.array ([1, 2.], dtype = object))가 int와 float을 혼합하는 오류 원인을 던집니까? – bcollins

+0

F (np.array ([1, 2.], dtype = object))에 대한 플로팅 반환 값은 정상입니다. – Olexiy

답변

2

아마 가장 간단한이 np.array을 통해 내용을 실행하고 결과 유형 확인하는 것입니다 :

a = np.array([1., 2.], dtype=object) 
b = np.array(['1.', '2.'], dtype=object) 
c = np.array([1, 2], dtype=object) 
d = np.array([1, 2.], dtype=object) 
e = np.array(['hello'], dtype=object) 
f = np.array([1, 'hello'], dtype=object) 

>>> np.array(list(a)).dtype 
dtype('float64') 
>>> np.array(list(b)).dtype 
dtype('S2') 
>>> np.array(list(c)).dtype 
dtype('int32') 
>>> np.array(list(d)).dtype 
dtype('float64') 
>>> np.array(list(e)).dtype 
dtype('S5') 

그것은 오류를 높이기 위해 실패를 호환되지 않는 유형의 경우에 그 NumPy와의 행동이 아니므 :

>>> np.array(list(f)).dtype 
dtype('S5') 
+0

고마워요! 오류를 발생시키는 것은 실제로 쉽습니다. np.all (new_array == old_array) – Olexiy

1

하지 않음이 가장 개체 관리를 효율적으로,하지만 어떻게되어 있는지 아부 t :

def F(a): 
    unique_types = set([type(i) for i in list(a)]) 
    if len(unique_types) > 1: 
     raise ValueError('data types not consistent') 
    else: 
     return unique_types.pop() 
관련 문제