返回物件的Python型別的標量資料型別或NumPy等效型別


要返回物件的Python型別的標量資料型別或NumPy等效型別,請使用numpy.obj2sctype()方法。第一個引數是要返回其型別的物件。如果提供了預設引數,則返回無法確定其型別的物件。如果沒有給出,則為這些物件返回None。

步驟

首先,匯入所需的庫 -

import numpy as np

要返回物件的 Python 型別 的標量資料型別或 NumPy 等效型別,請使用 numpy.obj2sctype() 方法 -

print("Using the obj2sctype() method in Numpy
")

檢查int -

print("Result...",np.obj2sctype(np.array([45, 89])))
print("Result...",np.obj2sctype(np.array([389, 7985])))

檢查float -

print("Result...",np.obj2sctype(np.float32))
print("Result...",np.obj2sctype(np.float64))
print("Result...",np.obj2sctype(np.array([5., 25., 40.])))

檢查complex -

print("Result...",np.obj2sctype(np.array([5.6j]))

示例

import numpy as np

# To return the scalar dtype or NumPy equivalent of Python type of an object, use the numpy.obj2sctype() method.
# The 1st parameter is the object of which the type is returned
# The default parameter, if given, is returned for objects whose types cannot be determined.
# If not given, None is returned for those objects.
print("Using the obj2sctype() method in Numpy
") # checking for int print("Result...",np.obj2sctype(np.array([45, 89]))) print("Result...",np.obj2sctype(np.array([389, 7985]))) # checking for float print("Result...",np.obj2sctype(np.float32)) print("Result...",np.obj2sctype(np.float64)) print("Result...",np.obj2sctype(np.array([5., 25., 40.]))) # checking for complex print("Result...",np.obj2sctype(np.array([5.6j])))

輸出

Using the obj2sctype() method in Numpy

Result... <class 'numpy.int64'>
Result... <class 'numpy.int64'>
Result... <class 'numpy.float32'>
Result... <class 'numpy.float64'>
Result... <class 'numpy.float64'>
Result... <class 'numpy.complex128'>

更新日期: 2022-02-24

208 瀏覽

職業生涯開啟

完成課程以獲得認證

開始
廣告