Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
The truth value of a Series in pandas can be ambiguous, as it can contain multiple values. To check if a Series is empty, you can use the .empty
attribute:
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.empty) # False
s = pd.Series([])
print(s.empty) # True
Watch a video course
Python - The Practical Guide
To check if any of the values in a Series are true, you can use the .any()
method:
s = pd.Series([True, False, False])
print(s.any()) # True
s = pd.Series([False, False, False])
print(s.any()) # False
To check if all of the values in a Series are true, you can use the .all()
method:
s = pd.Series([True, True, True])
print(s.all()) # True
s = pd.Series([True, False, True])
print(s.all()) # False
To check the single element of a series you can use .item()
method:
s = pd.Series([1,2,3])
print(s.item()) # 1
To check the boolean value of a series you can use .bool()
method:
s = pd.Series([1,2,3])
print(s.bool()) # True
It is also important to note that a series with at least one non-NaN value will return True
while a series containing only NaN will return False
.