简体   繁体   中英

Is a number float64?

I have a number

eg

a = 1.22373

type(a) is float

Like wise I want to find if a number is

float64 

or not.

How I will find using Python or NumPy?

Use isinstance :

>>> f = numpy.float64(1.4)
>>> isinstance(f, numpy.float64)
True
>>> isinstance(f, float)
True

numpy.float64 is inherited from python native float type. That because it is both float and float64 (@Bakuriu thx for pointing out). But if you will check python float instance variable for float64 type you will get False in result:

>>> f = 1.4
>>> isinstance(f, numpy.float64)
False
>>> isinstance(f, float)
True

I find this is the most readable method for checking Numpy number types

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')

If you are comparing numpy types only, it may be better to base your comparison on the number identifying each dtype, which is what the underlying C code does. On my system, 12 is the number for np.float64 :

>>> np.dtype(np.float64).num
12
>>> np.float64(5.6).dtype.num
12
>>> np.array([5.6]).dtype.num
12

To use it with non-numpy values also, you could duck-type your way through it with something like:

def isdtype(a, dt=np.float64):
    try:
        return a.dtype.num == np.dtype(dt).num
    except AttributeError:
        return False

If you're working with Series or Arrays, also checkout pandas.api.types.is_float_dtype() , which can be applied to Series or on a set of dtypes ; eg:

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()

See also:

  • pandas.api.types.is_integer_dtype()
  • pandas.api.types.is_numeric_dtype()

etc.

See https://pandas.pydata.org/pandas-docs/version/1.1.4/reference/api/pandas.api.types.is_bool_dtype.html and following pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM