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 - Check if the Pandas Index only consists of booleans
To check if a Pandas Index only consists of boolean values, use the is_boolean() method. This method returns True if all index values are boolean (True or False), otherwise False.
Syntax
index.is_boolean()
Return Value
Returns True if the index contains only boolean values, False otherwise.
Example with Boolean Index
Let's create an index with only boolean values and check using is_boolean() ?
import pandas as pd
# Creating Pandas index with boolean values
index = pd.Index([True, True, False, False, True, True, True])
# Display the Pandas index
print("Pandas Index...\n", index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n", index.size)
# Return the dtype of the data
print("\nThe dtype object...\n", index.dtype)
# Check whether index values have only booleans
print("\nIndex values only consists of booleans?\n", index.is_boolean())
Pandas Index... Index([True, True, False, False, True, True, True], dtype='object') Number of elements in the index... 7 The dtype object... object Index values only consists of booleans? True
Example with Mixed Data Types
Now let's see what happens when the index contains non-boolean values ?
import pandas as pd
# Creating index with mixed data types
mixed_index = pd.Index([True, False, 1, 0, 'True'])
# Display the index
print("Mixed Index...\n", mixed_index)
# Check if it contains only booleans
print("\nIndex values only consists of booleans?\n", mixed_index.is_boolean())
# Creating index with integers
int_index = pd.Index([1, 0, 1, 0])
print("\nInteger Index...\n", int_index)
print("Index values only consists of booleans?\n", int_index.is_boolean())
Mixed Index... Index([True, False, 1, 0, 'True'], dtype='object') Index values only consists of booleans? False Integer Index... Index([1, 0, 1, 0], dtype='int64') Index values only consists of booleans? False
Key Points
- The method only returns
Truefor actual boolean values (True/False) - Integer values like 1 and 0 are not considered boolean
- String representations like 'True' are not considered boolean
- The index dtype doesn't need to be 'bool' for this method to return
True
Conclusion
The is_boolean() method provides a quick way to verify if a Pandas Index contains only boolean values. It strictly checks for True and False values, not their numeric or string equivalents.
Advertisements
