Pandas Series.any()
Pandas Series.any() Tutorial
In this tutorial, we'll explore the Series.any()
method in Pandas, which is used to determine if any element in a Pandas Series evaluates to True
based on a specified condition, with examples.
The syntax of Series.any()
is:
Series.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
where
Parameter | Description |
---|---|
axis | [Optional] The axis along which the any() method is applied. Default is 0 (along rows). |
bool_only | [Optional] If True , only boolean-type Series are considered. Default is None . |
skipna | [Optional] If True , NA values are skipped. Default is True . |
level | [Optional] For a multi-level index, this specifies the level to check. Default is None . |
The Series.any()
method returns True
if any element in the Series is True
based on the specified conditions set by the parameters; otherwise, it returns False
.
Examples for Pandas Series.any() function
1. Check if any element is True (boolean Series) using Series.any()
In this example, we'll take a series with boolean values bool_series
, and use Series.any()
to check if any element in the boolean Series is True
.
Python Program
import pandas as pd
# Create a boolean series
bool_series = pd.Series([False, True, True])
# Check if any element is True
if bool_series.any():
print("Atleast one element is True.")
else:
print("None of the elements is True.")
Output
Atleast one element is True.
Let us take all elements in the Series as False, and rerun the program.
Python Program
import pandas as pd
# Create a boolean series
bool_series = pd.Series([False, False, False])
# Check if any element is True
if bool_series.any():
print("Atleast one element is True.")
else:
print("None of the elements is True.")
Output
None of the elements is True.
2. Check if any element is greater than 20 using Series.any()
In this example, we'll take a Series with integer values int_series
, use Series.any()
to check if any element in the given Series is greater than 20.
Python Program
import pandas as pd
# Create an int series
int_series = pd.Series([10, 15, 25, 40, 0, 5])
# Check if any element is greater than 20
if (int_series > 20).any():
print("Atleast one element is greater than 20.")
else:
print("None of the elements is greater than 20.")
Output
Atleast one element is greater than 20.
Now, let us take all the elements in the series such that they are less than 20.
Python Program
import pandas as pd
# Create an int series
int_series = pd.Series([10, 15, 0, 5])
# Check if any element is greater than 20
if (int_series > 20).any():
print("Atleast one element is greater than 20.")
else:
print("None of the elements is greater than 20.")
Output
None of the elements is greater than 20.
Summary
In this tutorial, we've covered the Series.any()
method in Pandas, which is useful for checking whether any element in a Series satisfies certain conditions.