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
Selected Reading
Python - Display True for infinite values in a Pandas DataFrame
When working with numerical data in Pandas, you may encounter infinite values. You can identify and display True for infinite values using the isin() method or np.isinf() function.
Creating a DataFrame with Infinite Values
First, let's create a DataFrame containing some infinite values using np.inf −
import pandas as pd
import numpy as np
# Create DataFrame with infinite values
data = {"Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf]}
dataFrame = pd.DataFrame(data)
print("DataFrame...")
print(dataFrame)
DataFrame... Reg_Price 0 7000.506 1 inf 2 5000.000 3 inf 4 9000.758 5 6000.000 6 900.000 7 inf
Method 1: Using isin() Method
The isin() method checks if values are contained in the provided list and returns True for infinite values −
import pandas as pd
import numpy as np
data = {"Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf]}
dataFrame = pd.DataFrame(data)
# Display True for infinite values
result = dataFrame.isin([np.inf, -np.inf])
print("Boolean mask for infinite values...")
print(result)
Boolean mask for infinite values... Reg_Price 0 False 1 True 2 False 3 True 4 False 5 False 6 False 7 True
Method 2: Using np.isinf() Function
You can also use NumPy's isinf() function to detect infinite values directly −
import pandas as pd
import numpy as np
data = {"Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000, 900, np.inf]}
dataFrame = pd.DataFrame(data)
# Using np.isinf() to detect infinite values
result = np.isinf(dataFrame)
print("Boolean mask using np.isinf()...")
print(result)
# Count total infinite values
count = np.isinf(dataFrame).values.sum()
print(f"\nTotal infinity values count: {count}")
Boolean mask using np.isinf()... Reg_Price 0 False 1 True 2 False 3 True 4 False 5 False 6 False 7 True Total infinity values count: 3
Comparison
| Method | Syntax | Advantage |
|---|---|---|
isin() |
df.isin([np.inf, -np.inf]) |
Handles both positive and negative infinity |
np.isinf() |
np.isinf(df) |
Direct NumPy function, more concise |
Conclusion
Both isin([np.inf, -np.inf]) and np.isinf() effectively identify infinite values in DataFrames. Use np.isinf() for simplicity or isin() when you need more control over specific values to check.
Advertisements
