Python | Filter out integers from float numpy array

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)

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# filtering integers from numpy array
# containing integers and float
  
import numpy as np
  
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
  
# printing initial array
print ("initial array : ", str(ini_array))
  
# filtering integers
result = ini_array[ini_array != ini_array.astype(int)]
  
# printig resultant
print ("final array", result)

chevron_right


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()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# filtering integers from numpy array
# containing integers and float
  
import numpy as np
  
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
  
# printing initial array
print ("initial array : ", str(ini_array))
  
# filtering integers
result = ini_array[~np.equal(np.mod(ini_array, 1), 0)]
  
# printing resultant
print ("final array : ", str(result))

chevron_right


Output:

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

 
Method #3: Using np.isclose()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate 
# filtering integers from numpy array
# containing integers and float
  
import numpy as np
  
# initialising array
ini_array = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
  
# printing initial array
print ("initial array : ", str(ini_array))
  
# filtering integers
mask = np.isclose(ini_array, ini_array.astype(int))
result = ini_array[~mask]
  
# printing resultant
print ("final array : ", str(result))

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.