Pandas DataFrame bool() Method
In this tutorial, we will learn the Python pandas DataFrame.bool()
method. It returns the bool of a single element DataFrame. This must be a boolean scalar value, either True
or False
. It will raise ValueError
if the DataFrame does not have exactly 1 element or that element is not boolean.
The below shows the syntax of DataFrame.bool()
method.
Syntax
The syntax required to use this method is as follows.
DataFrame.bool()
Example 1: Checking a DataFrame using DataFrame.bool()
Method
The DataFrame.bool()
method return True
only when the DataFrame contains a single bool True element.
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [True]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
Once we run the program we will get the following result.
------DataFrame-------
column
0 True
Is the DataFrame contains single bool value: True
Example 2: Checking a DataFrame using DataFrame.bool()
Method
The DataFrame.bool()
method returns False
only when the DataFrame contains a single bool False element.
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [False]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
Once we run the program we will get the following result.
------DataFrame-------
column
0 False
Is the DataFrame contains single bool value: False
Example 3: The DataFrame.bool()
method raises ValueError
The DataFrame.bool()
method raises ValueError
if the DataFrame contains two elements.
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [True,True]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
Once we run the program we will get the following result.
------DataFrame-------
column
0 True
1 True
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Example: The DataFrame using DataFrame.bool()
method with integers
The DataFrame.bool()
method raises ValueError
if the DataFrame contains an integer element.
#importing pandas library
import pandas as pd
df=pd.DataFrame({'column': [1]})
print("------DataFrame-------")
print(df)
print("Is the DataFrame contains single bool value:",df.bool())
Once we run the program we will get the following result.
------DataFrame-------
column
0 1
ValueError: bool cannot act on a non-boolean single element DataFrame
Conclusion
In this tutorial, we learned the python pandas DataFrame.bool()
method. By solving different examples we understood how this method works.