在 Python 中返回輸入陣列的公共標量型別


要返回輸入陣列的公共標量型別,請在 Python NumPy 中使用 numpy.common_type() 方法。第一個引數是輸入陣列。返回型別始終為不精確(即浮點數)標量型別,即使所有陣列都是整數陣列。如果其中一個輸入是整數陣列,則返回的最小精度型別為 64 位浮點數資料型別。

除 int64 和 uint64 之外的所有輸入陣列都可以安全地轉換為返回的資料型別,而不會丟失資訊。

步驟

首先,匯入所需的庫 -

import numpy as np

要返回輸入陣列的公共標量型別,請使用 numpy.common_type() 方法 -

print("Using the common_type() method in Numpy\n")
print("Result...",np.common_type(np.arange(3,dtype=np.float32)))
print("Result...",np.common_type(np.arange(3,dtype=np.float32), np.arange(2)))
print("Result...",np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3,dtyp =np.int32), np.arange(2))) Example

示例

import numpy as np

# To return a scalar type which is common to the input arrays, use the numpy.common_type() method in Python Numpy.
# The 1st parameter is the input array(s).

print("Using the common_type() method in Numpy\n")
print("Result...",np.common_type(np.arange(3,dtype=np.float32)))
print("Result...",np.common_type(np.arange(3,dtype=np.float32), np.arange(2)))
print("Result...",np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3,dtype=np.int32), np.arange(2)))

輸出

Using the common_type() method in Numpy

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

更新於: 2022-02-24

369 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告