How do I find out if a numpy array contains integers?

后端 未结 5 1181
一个人的身影
一个人的身影 2021-02-03 18:46

I know there is a simple solution to this but can\'t seem to find it at the moment.

Given a numpy array, I need to know if the array contains integers.

Checking

5条回答
  •  渐次进展
    2021-02-03 19:39

    Numpy's issubdtype() function can be used as follows:

    import numpy as np
    
    size=(3,3)
    A = np.random.randint(0, 255, size)
    B = np.random.random(size)
    
    print 'Array A:\n',  A
    print 'Integers:', np.issubdtype(A[0,0], int)
    print 'Floats:', np.issubdtype(A[0,0], float)
    
    print '\nArray B:\n',  B
    print 'Integers:', np.issubdtype(B[0,0], int)
    print 'Floats:', np.issubdtype(B[0,0], float)
    

    Results:

    Array A:
    [[  9 224  33]
     [210 117  83]
     [206 139  60]]
    Integers: True
    Floats: False
    
    Array B:
    [[ 0.54221849  0.96021118  0.72322367]
     [ 0.02207826  0.55162813  0.52167972]
     [ 0.74106348  0.72457807  0.9705301 ]]
    Integers: False
    Floats: True
    

    PS. Keep in mind that the elements of an array are always of the same datatype.

提交回复
热议问题