Python | Filter out integers from float numpy array
Last Updated :
06 Jan, 2023
Given a numpy array, the task is to filter out integers from an array containing float and integers. Let’s see few methods to solve a given task.
Method #1 : Using astype(int)
Python3
import numpy as np
ini_array = np.array([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])
print ( "initial array : " , str (ini_array))
result = ini_array[ini_array ! = ini_array.astype( int )]
print ( "final array" , result)
|
Method #2: Using np.equal() and np.mod()
Python3
import numpy as np
ini_array = np.array([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])
print ( "initial array : " , str (ini_array))
result = ini_array[~np.equal(np.mod(ini_array, 1 ), 0 )]
print ( "final array : " , str (result))
|
Method #3: Using np.isclose()
Python3
import numpy as np
ini_array = np.array([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])
print ( "initial array : " , str (ini_array))
mask = np.isclose(ini_array, ini_array.astype( int ))
result = ini_array[~mask]
print ( "final array : " , str (result))
|
Method #4 : Using round()
Approach is to use the numpy.isreal() function and apply additional filtering to select only those elements that are not equal to their integer counterparts.
Python3
import numpy as np
ini_array = np.array([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])
print ( "initial array : " , str (ini_array))
mask = np.isreal(ini_array)
result = ini_array[mask]
result = result[result ! = np. round (result)]
print ( "final array : " , str (result))
|
Output:
initial array : [1. 1.2 2.2 2. 3. 2. ]
final array : [1.2 2.2]
Time complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...