Using numpy.isfinite() function (4 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

Introduction

In this tutorial, we delve deep into the numpy.isfinite() function, a powerful tool provided by NumPy, an essential library in the world of Python programming. NumPy is widely known for its array objects and the broad array of functions that operate on arrays to perform various numerical computations efficiently. Among these functions, numpy.isfinite() holds a unique place for data validation and cleanup tasks. Understanding how to utilize it effectively can significantly elevate your data handling tasks. We will explore numpy.isfinite() through 4 progressively complex examples, highlighting its practical applications in real-world scenarios.

What is numpy.isfinite() Used for?

The numpy.isfinite() function is used to test element-wise whether it is a finite number or not, returning a boolean array as the output. An ‘inf’ (infinity) or ‘nan’ (not a number) in the input array will yield False for that position in the output array, while all other values will return True. This function is crucial in data cleaning processes, especially when dealing with real-world data that might be imperfect or incomplete.

Example 1: Basic Example

import numpy as np

# Create an array
arr = np.array([1, 2, np.nan, np.inf, -np.inf, 0])

# Use isfinite
result = np.isfinite(arr)

# Print result
print(result)

Output:

[ True  True False False False  True]

This basic example demonstrates the immediate functionality of numpy.isfinite(), allowing us to quickly identify which elements in our array are finite.

Example 2: Working with 2D Arrays

import numpy as np

# Create a 2D array
arr2D = np.array([[1, 2, np.nan], [np.inf, -np.inf, 0]])

# Applying isfinite on 2D array
result2D = np.isfinite(arr2D)

# Print result
print(result2D)

Output:

[[ True  True False]
  [False False  True]]

Moving to a more complex array structure, this example illustrates how numpy.isfinite() can be applied to 2D arrays, reflecting its versatility across different data shapes.

Example 3: Filtering Finite Values

import numpy as np

# Create an array with mixed values
mixedArr = np.array([1, 2, np.nan, np.inf, -np.inf, 3])

# Filter and get only finite values
finiteValues = mixedArr[np.isfinite(mixedArr)]

# Print finite values
print(finiteValues)

Output:

[1. 2. 3.]

Here, we leverage numpy.isfinite() to filter and extract only the finite values from an array. This application is particularly useful for preprocessing data before conducting any further analysis or computation.

Example 4: Integration with Pandas DataFrame

import numpy as np
import pandas as pd

# Create a DataFrame with some 'inf' and 'nan' values
df = pd.DataFrame({'A': [1, np.inf, 3], 'B': [np.nan, 2, np.inf]})

# Use applymap to apply isfinite on the DataFrame
finiteDf = df.applymap(np.isfinite)

# Print the modified DataFrame
print(finiteDf)

Output:

       A      B
 0   True  False
 1  False  False
 2   True   True

This advanced example shows how numpy.isfinite() function can be integrated with Pandas DataFrames, a common data structure used in data science, to identify finite values across the DataFrame. It demonstrates the function’s utility in a broader scope, beyond simple arrays.

Conclusion

Throughout these examples, we’ve observed how numpy.isfinite() can be a critical tool in data preprocessing, offering a straightforward method to identify and handle non-finite values within an array or DataFrame. Its simplistic interface coupled with powerful functionality makes it an indispensable function for any data scientist or Python developer working with numerical data.