![]() |
VOOZH | about |
Sometimes, a NumPy array contains both integers and floats and we want to remove only the integers while keeping the float values. This can be done in multiple ways using NumPy functions.
This method compares each element of the array with its integer-converted version. If both values are nearly equal, element is treated as an integer and removed.
In this example, we use np.isclose() with integer conversion to identify integers and exclude them.
Array: [1. 1.2 2.2 2. 3. 2. ] Result: [1.2 2.2]
Explanation:
This method uses modular arithmetic. By dividing each element by 1 (np.mod(arr, 1)), the fractional part is extracted. If the remainder is 0, the number is an integer. We then exclude those integers.
In this example, we use np.mod() to find non-integers and filter them out.
Array: [1. 1.2 2.2 2. 3. 2. ] Result: [1.2 2.2]
Explanation:
This method casts the entire array to integers and then compares it with the original array. Wherever values match, those are integers and can be filtered out. It’s simple but may be less precise for floating-point edge cases.
In this example, we compare array elements with their integer values and filter out integers.
Array: [1. 1.2 2.2 2. 3. 2. ] Result: [1.2 2.2]
Explanation:
This method rounds each element and compares it with the original. If both are equal, number is considered an integer and removed. However, due to floating-point precision issues, it may not always be as accurate as np.isclose().
In this example, we check if elements are different from their rounded versions and filter out integers.
Array: [1. 1.2 2.2 2. 3. 2. ] Result: [1.2 2.2]
Explanation: