Python | Filter integers from floating point array



Method # 1: Using astype (int)

# Python code for demonstration
# filtering integers from a numpy array
# contains integers and floats

 

import numpy as np

 
# initializing array

ini_array = np.array ([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])

 
# print the original array

print ( "initial array:" , str (ini_array))

 
# filtering integers

result = ini_array [ini_array! = ini_array.astype ( int )]

 
# result print

print ( "final array" , result)

Output:

 initial array: [1. 1.2 2.2 2. 3. 2.] final array [1.2 2.2] 

Method # 2: Using np.equal () and np .mod ()

# Python code for demonstration
# filtering integers numbers from a numpy array
# contains integers and floats

 

import numpy as np

  
# initializing array

ini_array = np.array ([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])

 
# printing the original array

print ( "initial array: " , str (ini_array))

 
# filtering integers

result = ini_array [~ np.equal (np.mod (ini_array, 1 ), 0 )]

 
# print result

print ( "final array:" , str (result))

Output:

 initial array: [1. 1.2 2.2 2. 3. 2.] final array: [1.2 2.2] 

Method # 3: Using np.isclose ()

# Python code for demonstration
# filtering integers from a numpy array
# contains integers and floats

 

import numpy as np

 
# ini initializing array

ini_array = np.array ([ 1.0 , 1.2 , 2.2 , 2.0 , 3.0 , 2.0 ])

 
# print the original array

print ( "initial array:" , str (ini_array))

 
# filtering integers

mask =   np.isclose (ini_array, ini_array.astype ( int ))

result = ini_array [~ mask]

 
# print result

print ( " final array: " , str (result))

Output:

 initial array: [1. 1.2 2.2 2. 3. 2.] final array: [1.2 2.2]