Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Filter out integers from float numpy array
When working with NumPy arrays containing both floats and integers, you may need to filter out integer values for data cleansing purposes. This article demonstrates two effective methods to remove integers from a float NumPy array using astype comparison and modulo operations.
Method 1: Using astype Comparison
The astype function converts array elements to integers. By comparing the original array with its integer-converted version, we can identify which elements are not integers ?
Example
import numpy as np
# Create array with mixed floats and integers
data_array = np.array([3.2, 5.5, 2.0, 4.1, 5])
print("Given array:")
print(data_array)
# Filter out integers by comparing with astype(int)
float_only = data_array[data_array != data_array.astype(int)]
print("Array without integers:")
print(float_only)
Given array: [3.2 5.5 2. 4.1 5. ] Array without integers: [3.2 5.5 4.1]
Method 2: Using Modulo Operation
This approach uses the modulo operator to check if a number has a fractional part. When dividing by 1, integers return 0 while floats return their fractional component ?
Example
import numpy as np
# Create array with mixed floats and integers
data_array = np.array([3.2, 5.5, 2.0, 4.1, 5])
print("Given array:")
print(data_array)
# Filter using modulo: keep elements where mod 1 is not zero
float_only = data_array[~np.equal(np.mod(data_array, 1), 0)]
print("Array without integers:")
print(float_only)
Given array: [3.2 5.5 2. 4.1 5. ] Array without integers: [3.2 5.5 4.1]
How It Works
Both methods create boolean masks to identify non-integer values:
- Method 1: Compares original values with their integer equivalents
- Method 2: Uses modulo to detect fractional parts
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
astype |
Faster | High | General use |
mod |
Slower | Medium | Mathematical clarity |
Conclusion
Use astype comparison for better performance and readability. The modulo method provides mathematical clarity but is computationally slower for large arrays.
