파이썬에서 numpy 유형을 식별하는 방법은 무엇입니까?
물체가 마비 유형을 가지고 있는지 어떻게 확실하게 판단할 수 있습니까?
저는 이 질문이 오리 유형의 철학에 어긋난다는 것을 알고 있지만, 아이디어는 함수(Scipy와 Numpy를 사용하는)가 numpy 유형으로 호출되지 않는 한 numpy 유형을 반환하지 않도록 하는 것입니다.이것은 다른 질문에 대한 해결책에서 나오지만, 저는 어떤 물체가 마비 유형을 가지고 있는지를 결정하는 일반적인 문제는 그들이 분리되어야 한다는 원래의 질문에서 충분히 멀리 떨어져 있다고 생각합니다.
기본 제공 사용type
유형을 가져오는 기능, 그러면 당신은 사용할 수 있습니다.__module__
정의된 위치를 확인하는 속성:
>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True
제가 생각해 낸 해결책은 다음과 같습니다.
isinstance(y, (np.ndarray, np.generic) )
그러나 모든 numpy 유형이 다음 중 하나로 보장된다는 것은 100% 명확하지 않습니다.np.ndarray
또는np.generic
그리고 이것은 아마도 버전이 견고하지 않을 것입니다.
오래된 질문이지만 저는 예를 들어 결정적인 답을 생각해냈습니다.저도 같은 문제가 있었고 명확한 답을 찾지 못했기 때문에 질문을 신선하게 유지하는 것이 나쁠 수 없습니다.중요한 것은 당신이 가지고 있는지 확인하는 것입니다.numpy
가져온 다음 실행합니다.isinstance
boole. 이것은 간단해 보이지만, 만약 당신이 다른 데이터 유형에서 약간의 계산을 하고 있다면, 이 작은 검사는 당신이 마비 벡터화된 작업을 시작하기 전에 빠른 테스트 역할을 할 수 있습니다.
##################
# important part!
##################
import numpy as np
####################
# toy array for demo
####################
arr = np.asarray(range(1,100,2))
########################
# The instance check
########################
isinstance(arr,np.ndarray)
그것은 실제로 당신이 무엇을 찾느냐에 달려 있습니다.
- 시퀀스가 실제로 다음과 같은지 여부를 테스트하려면
ndarray
,aisinstance(..., np.ndarray)
가장 쉬운 방법일 겁니다모듈이 다를 수 있으므로 백그라운드에서 numpy를 다시 로드하지 않도록 하십시오. 그렇지 않으면 문제가 없습니다.MaskedArrays
,matrix
,recarray
의 모든 하위 클래스입니다.ndarray
그러니 준비를 하셔야 합니다. - 스칼라가 numpy 스칼라인지 테스트하려면 상황이 좀 더 복잡해집니다.당신은 그것이 가지고 있는지 확인할 수 있습니다.
shape
그리고 adtype
기여하다.비교할 수 있습니다.dtype
목록에서 찾을 수 있는 기본 d타입으로.np.core.numerictypes.genericTypeRank
이 목록의 요소는 문자열이므로 다음을 수행해야 합니다.tested.dtype is np.dtype(an_element_of_the_list)
...
유형을 가져오려면 기본 제공 항목을 사용합니다.type
기능.와 함께in
연산자, 문자열이 포함되어 있는지 확인하여 유형이 numpy 유형인지 테스트할 수 있습니다.numpy
;
In [1]: import numpy as np
In [2]: a = np.array([1, 2, 3])
In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>
In [4]: 'numpy' in str(type(a))
Out[4]: True
(참고로 이 예제는 IPython에서 실행되었습니다.대화형 사용 및 빠른 테스트에 매우 유용합니다.)
로 고는 다음과 .type(numpy.ndarray)
입니다.type
부울 및 스칼라 유형에 주의해야 합니다.직관적이거나 쉽지 않은 일이라면 너무 낙담하지 마세요, 처음에는 고통입니다.
참고 항목: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy
>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True
부울과 함께하는 재미:
>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool # python equivalent
True
스칼라 유형에 대한 자세한 내용은 다음을 참조하십시오. - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in
>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True # generic integer
>>> isinstance(x[0], int)
False # but not a python int in this case
# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind
'b'
>>> np.dtype('int64').kind
'i'
>>> np.dtype('float').kind
'f'
>>> np.dtype('half').kind
'f'
# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False
# Down these paths there be dragons:
# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False # again, confusing the .dtype with a specific dtype
# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:
>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False # oh boy
>>> x[0].dtype == np.int
False # ya, no luck here either
>>> x[0].dtype == np.int_
False # or here
>>> x[0].dtype == np.uint64
True # have to end on a good note!
언급URL : https://stackoverflow.com/questions/12569452/how-to-identify-numpy-types-in-python
'programing' 카테고리의 다른 글
PHP의 메모리 제한을 2GB 이상으로 늘리는 방법은 무엇입니까? (0) | 2023.07.31 |
---|---|
구성 요소를 사용하지 않고 angular2 경로에서 외부 URL로 리디렉션하는 방법은 무엇입니까? (0) | 2023.07.31 |
SpringRequestMapping 경로 매개 변수가 있는 인코딩 슬래시(%2F)는 HTTP 400을 제공합니다. (0) | 2023.07.31 |
안드로이드에서 점선/점선을 만들려면 어떻게 해야 합니까? (0) | 2023.07.31 |
데몬의 오류 응답: 심을 생성하지 못했습니다. OCI 런타임을 생성하지 못했습니다. container_linux.go:380...Ubuntu WSL 2에서 도커를 사용하는 동안 (0) | 2023.07.31 |