In Python, how could you check if the type of a number is an integer without checking each integer type, i.e., 'int'
, 'numpy.int32'
, or 'numpy.int64'
?
I thought to try if int(val) == val
but this does not work when a float is set to an integer value (not type).
JavaScript
x
14
14
1
In [1]: vals = [3, np.ones(1, dtype=np.int32)[0], np.zeros(1, dtype=np.int64)[0], np.ones(1)[0]]
2
In [2]: for val in vals:
3
print(type(val)) :
4
if int(val) == val: :
5
print('{} is an int'.format(val)) :
6
<class 'int'>
7
3 is an int
8
<class 'numpy.int32'>
9
1 is an int
10
<class 'numpy.int64'>
11
0 is an int
12
<class 'numpy.float64'>
13
1.0 is an int
14
I want to filter out the last value, which is a numpy.float64
.
Advertisement
Answer
You can use isinstance
with a tuple argument containing the types of interest.
To capture all python and numpy integer types use:
JavaScript
1
2
1
isinstance(value, (int, np.integer))
2
Here is an example showing the results for several data types:
JavaScript
1
3
1
vals = [3, np.int32(2), np.int64(1), np.float64(0)]
2
[(e, type(e), isinstance(e, (int, np.integer))) for e in vals]
3
Result:
JavaScript
1
5
1
[(3, <type 'int'>, True),
2
(2, <type 'numpy.int32'>, True),
3
(1, <type 'numpy.int64'>, True),
4
(0.0, <type 'numpy.float64'>, False)]
5
A second example which is true only for int and int64:
JavaScript
1
2
1
[(e, type(e), isinstance(e, (int, np.int64))) for e in vals]
2
Result:
JavaScript
1
5
1
[(3, <type 'int'>, True),
2
(1, <type 'numpy.int32'>, False),
3
(0, <type 'numpy.int64'>, True),
4
(0.0, <type 'numpy.float64'>, False)]
5