How to find integers from a NumPy array in Python?
In this article, we will see how to find integers from a NumPy array in Python with the code example.
A NumPy array is a grid of values with the same datatype. There are a number of applications for NumPy arrays and a lot of libraries in Python are based on NumPy. If you are looking at this article, it is a good assumption that you have NumPy installed already, however, the installation is explained in a few lines.
Installation of NumPy
Open your command prompt and run the following command.
pip install numpy
This command should install everything that’s required. To check if everything was installed correctly, open your Python shell and run the following code.
If the installation was successful, the code should not produce any errors. Let’s now jump into the actual task.
Python program to find integers from a NumPy array
One of the properties of NumPy arrays is that they store values in a grid and all the values have the same datatype. In a situation where both floats and integers exist in the NumPy array, the integers will be converted into floating-point numbers. Our task is to extract the integers from a NumPy array.
We will choose a method that is quite different but does the job perfectly fine. It is known that all integers are divisible by 1. So we will use the following condition as a test for being an integer:
number % 1 == 0
Now, let’s try to implement this with the following code:
import numpy as np def isInt(num): return np.equal(np.mod(num, 1), 0) arr = np.array([1.0, 2.3, 3, 4.0, 4.001]) for num in arr: if isInt(num): print(num, "is an integer")
We have implemented the above-mentioned condition using NumPy functions. Since there are floating-point values in the NumPy array, all of them will be converted into floating-point numbers. We use the isInt() function to verify is a value is an integer.
The output for the above code is:
1.0 is an integer 3.0 is an integer 4.0 is an integer
I hope you found the article helpful in finding the integers from a NumPy array.