[英]Is a number float64?
我有一个号码
例如
a = 1.22373
type(a) is float
就像明智的,我想找出一个数字是否是
float64
或不。
我将如何使用 Python 或 NumPy 查找?
使用isinstance :
>>> f = numpy.float64(1.4)
>>> isinstance(f, numpy.float64)
True
>>> isinstance(f, float)
True
numpy.float64 继承自 python 原生浮点类型。 那是因为它既是 float 又是 float64 (@Bakuriu thx 指出)。 但是,如果您将检查 float64 类型的 python float 实例变量,您将在结果中得到False
:
>>> f = 1.4
>>> isinstance(f, numpy.float64)
False
>>> isinstance(f, float)
True
我发现这是检查 Numpy 数字类型的最易读的方法
import numpy as np
npNum = np.array([2.0])
if npNum.dtype == np.float64:
print('This array is a Float64')
# or if checking for multiple number types:
if npNum.dtype in [
np.float32, np.float64,
np.int8, np.uint8,
np.int16, np.uint16,
np.int32, np.uint32,
np.int64, np.uint64
]:
print('This array is either a float64, float32 or an integer')
如果您只比较 numpy 类型,最好根据标识每个 dtype 的数字进行比较,这就是底层 C 代码所做的。 在我的系统上, 12 是np.float64
的数字:
>>> np.dtype(np.float64).num
12
>>> np.float64(5.6).dtype.num
12
>>> np.array([5.6]).dtype.num
12
要将它与非 numpy 值一起使用,您可以使用以下内容通过它来输入:
def isdtype(a, dt=np.float64):
try:
return a.dtype.num == np.dtype(dt).num
except AttributeError:
return False
如果您正在使用 Series 或 Arrays,还可以pandas.api.types.is_float_dtype()
,它可以应用于 Series 或一组dtypes
; 例如:
dts = df.dtypes # Series of dtypes with the colnames as the index
is_floating = dts.apply(pd.api.types.is_float_dtype)
floating_cols_names = dts[is_floating].index.tolist()
也可以看看:
pandas.api.types.is_integer_dtype()
pandas.api.types.is_numeric_dtype()
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.