numpy dtype을 기본 파이썬 유형으로 변환
numpy dtype이 있으면 가장 가까운 python 데이터 유형으로 자동 변환하는 방법은 무엇입니까? 예를 들어
numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32 -> "python int"
numpy.int16 -> "python int"
이 모든 경우의 매핑을 생각해 볼 수는 있지만 numpy는 dtype을 가장 가까운 원시 파이썬 유형으로 자동 변환하는 방법을 제공합니까? 이 매핑은 철저 할 필요는 없지만 가까운 파이썬 아날로그를 가진 일반적인 dtype을 변환해야합니다. 나는 이것이 이미 어딘가에 있다고 생각합니다.
val.item()
대부분의 NumPy 값을 기본 Python 유형으로 변환하는 데 사용하십시오 .
import numpy as np
# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval)) # <class 'float'>
# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item()) # <class 'long'>
type(np.int16(0).item()) # <class 'int'>
type(np.cfloat(0).item()) # <class 'complex'>
type(np.datetime64(0, 'D').item()) # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item()) # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...
(또 다른 방법은 np.asscalar(val)
NumPy 1.16부터 더 이상 사용되지 않습니다).
궁금한 점이 있으시면 시스템에 대한 NumPy 배열 스칼라 변환 표 를 작성하십시오.
for name in dir(np):
obj = getattr(np, name)
if hasattr(obj, 'dtype'):
try:
if 'time' in name:
npn = obj(0, 'D')
else:
npn = obj(0)
nat = npn.item()
print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
except:
pass
등 일부 시스템에는 기본 파이썬에 해당이없는 몇 NumPy와 유형이있다 : clongdouble
, clongfloat
, complex192
, complex256
, float128
, longcomplex
, longdouble
와 longfloat
. 이를 사용하기 전에 가장 가까운 NumPy로 변환해야합니다 .item()
.
numpy 유형과 표준 파이썬이 혼합되어 있음을 발견했습니다. 모든 numpy 유형이에서 파생되었으므로 numpy.generic
모든 것을 파이썬 표준 유형으로 변환하는 방법은 다음과 같습니다.
if isinstance(obj, numpy.generic):
return numpy.asscalar(obj)
(numpy.array 또는 numpy 스칼라 OR 기본 유형 또는 numpy.darray) 기본 유형으로 변환하려면 다음을 수행하십시오.
converted_value = getattr(value, "tolist", lambda: value)()
tolist는 스칼라 또는 배열을 파이썬 기본 유형으로 변환합니다. 기본 람다 함수는 값이 이미 고유 한 경우를 처리합니다.
어때요 :
In [51]: dict([(d, type(np.zeros(1,d).tolist()[0])) for d in (np.float32,np.float64,np.uint32, np.int16)])
Out[51]:
{<type 'numpy.int16'>: <type 'int'>,
<type 'numpy.uint32'>: <type 'long'>,
<type 'numpy.float32'>: <type 'float'>,
<type 'numpy.float64'>: <type 'float'>}
변환하려는 객체 의 item()
메소드 를 호출 할 수도 있습니다 .
>>> from numpy import float32, uint32
>>> type(float32(0).item())
<type 'float'>
>>> type(uint32(0).item())
<type 'long'>
tolist()
is a more general approach to accomplish this. It works in any primitive dtype and also in arrays or matrices.
I doesn't actually yields a list if called from primitive types:
numpy == 1.15.2
>>> import numpy as np
>>> np_float = np.float64(1.23)
>>> print(type(np_float), np_float)
<class 'numpy.float64'> 1.23
>>> listed_np_float = np_float.tolist()
>>> print(type(listed_np_float), listed_np_float)
<class 'float'> 1.23
>>> np_array = np.array([[1,2,3.], [4,5,6.]])
>>> print(type(np_array), np_array)
<class 'numpy.ndarray'> [[1. 2. 3.]
[4. 5. 6.]]
>>> listed_np_array = np_array.tolist()
>>> print(type(listed_np_array), listed_np_array)
<class 'list'> [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
I think you can just write general type convert function like so:
import numpy as np
def get_type_convert(np_type):
convert_type = type(np.zeros(1,np_type).tolist()[0])
return (np_type, convert_type)
print get_type_convert(np.float32)
>> (<type 'numpy.float32'>, <type 'float'>)
print get_type_convert(np.float64)
>> (<type 'numpy.float64'>, <type 'float'>)
This means there is no fixed lists and your code will scale with more types.
numpy holds that information in a mapping exposed as typeDict
so you could do something like the below::
>>> import __builtin__
>>> import numpy as np
>>> {v: k for k, v in np.typeDict.items() if k in dir(__builtin__)}
{numpy.object_: 'object',
numpy.bool_: 'bool',
numpy.string_: 'str',
numpy.unicode_: 'unicode',
numpy.int64: 'int',
numpy.float64: 'float',
numpy.complex128: 'complex'}
If you want the actual python types rather than their names, you can do ::
>>> {v: getattr(__builtin__, k) for k, v in np.typeDict.items() if k in vars(__builtin__)}
{numpy.object_: object,
numpy.bool_: bool,
numpy.string_: str,
numpy.unicode_: unicode,
numpy.int64: int,
numpy.float64: float,
numpy.complex128: complex}
Sorry to come late to the partly, but I was looking at a problem of converting numpy.float64
to regular Python float
only. I saw 3 ways of doing that:
npValue.item()
npValue.astype(float)
float(npValue)
Here are the relevant timings from IPython:
In [1]: import numpy as np
In [2]: aa = np.random.uniform(0, 1, 1000000)
In [3]: %timeit map(float, aa)
10 loops, best of 3: 117 ms per loop
In [4]: %timeit map(lambda x: x.astype(float), aa)
1 loop, best of 3: 780 ms per loop
In [5]: %timeit map(lambda x: x.item(), aa)
1 loop, best of 3: 475 ms per loop
It sounds like float(npValue)
seems much faster.
My approach is a bit forceful, but seems to play nice for all cases:
def type_np2py(dtype=None, arr=None):
'''Return the closest python type for a given numpy dtype'''
if ((dtype is None and arr is None) or
(dtype is not None and arr is not None)):
raise ValueError(
"Provide either keyword argument `dtype` or `arr`: a numpy dtype or a numpy array.")
if dtype is None:
dtype = arr.dtype
#1) Make a single-entry numpy array of the same dtype
#2) force the array into a python 'object' dtype
#3) the array entry should now be the closest python type
single_entry = np.empty([1], dtype=dtype).astype(object)
return type(single_entry[0])
Usage:
>>> type_np2py(int)
<class 'int'>
>>> type_np2py(np.int)
<class 'int'>
>>> type_np2py(str)
<class 'str'>
>>> type_np2py(arr=np.array(['hello']))
<class 'str'>
>>> type_np2py(arr=np.array([1,2,3]))
<class 'int'>
>>> type_np2py(arr=np.array([1.,2.,3.]))
<class 'float'>
Translate the whole ndarray instead one unit data object:
def trans(data):
"""
translate numpy.int/float into python native data type
"""
result = []
for i in data.index:
# i = data.index[0]
d0 = data.iloc[i].values
d = []
for j in d0:
if 'int' in str(type(j)):
res = j.item() if 'item' in dir(j) else j
elif 'float' in str(type(j)):
res = j.item() if 'item' in dir(j) else j
else:
res = j
d.append(res)
d = tuple(d)
result.append(d)
result = tuple(result)
return result
However, it takes some minutes when handling large dataframes. I am also looking for a more efficient solution. Hope a better answer.
참고URL : https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types
'Programing' 카테고리의 다른 글
메모리에서 객체 크기를 얻는 방법? (0) | 2020.05.13 |
---|---|
비밀번호없이 생성 된 OpenSSH 개인 키에 비밀번호를 추가하려면 어떻게합니까? (0) | 2020.05.13 |
C #에서 동일한 클래스의 다른 생성자에서 오버로드 된 생성자를 호출 할 수 있습니까? (0) | 2020.05.13 |
주어진 날짜의 정확한 주 번호를 얻으십시오 (0) | 2020.05.13 |
Mac에 gitk 설치 (0) | 2020.05.13 |