Python - Filter out integers from float numpy array


As part of data cleansing activities, we may sometimes need to take out the integers present in a list. In this article we will have an array containing both floats and integers. We will remove the integers from the array and print out the floats.

With astype

The astype function will be used to find if an element from the array is an integer or not. Accordingly we will decide to keep or remove the element from the array and store it in the result set.

Example

 Live Demo

import numpy as np

# initialising array
A_array = np.array([3.2, 5.5, 2.0, 4.1,5])

print("Given array :\n ", A_array)

# Only integers
res = A_array[A_array != A_array.astype(int)]

# result
print("Array without integers:\n", res)

Output

Running the above code gives us the following result −

Given array :
   [3.2 5.5 2. 4.1 5. ]
Array without integers:
   [3.2 5.5 4.1]

With equal and mod

In this approach we apply the mod function to each element of the array and check that on dividing the result is zero or not. If the result is not a zero then it is considered a float and kept as the result.

Example

 Live Demo

import numpy as np

# initialising array
A_array = np.array([3.2, 5.5, 2.0, 4.1,5])

print("Given array :\n ", A_array)

# Only integers
res = A_array[~np.equal(np.mod(A_array, 1), 0)]

# result
print("Array without integers:\n", res)

Output

Running the above code gives us the following result −

Given array :
   [3.2 5.5 2. 4.1 5. ]
Array without integers:
   [3.2 5.5 4.1]

Updated on: 22-Jul-2020

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements