Check if Any Element is True in DataFrame
To check if any element is True or non-zero or non-empty in DataFrame, over an axis, call any() method on this DataFrame.
In this tutorial, we will learn the syntax of DataFrame.any() method and how to use this method to check if at least one element in DataFrame along an axis is True or non-zero or non-empty.
Syntax
The syntax of pandas DataFrame.any() method is
DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
where
Parameter | Value | Description |
---|---|---|
axis | {0 or ‘index’, 1 or ‘columns’, None}. default value is 0. | Indicate which axis or axes should be reduced. 0 / ‘index’ : reduce the index, return a Series whose index is the original column labels. 1 / ‘columns’ : reduce the columns, return a Series whose index is the original index. None : reduce all axes, return a scalar. |
bool_only | bool. default value is None. | Include only boolean columns. If None, will attempt to use everything, then use only boolean data. Not implemented for Series. |
skipna | bool. default value is True. | Exclude NA/null values. If the entire row/column is NA and skipna is True, then the result will be False, as for an empty row/column. If skipna is False, then NA are treated as True, because these are not equal to zero. |
level | int or level name. default value is None. | If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series. |
**kwargs | any. default value is None. | Additional keywords have no effect but might be accepted for compatibility with NumPy. |
Return Value
- DataFrame: If level is specified or
- Series
Examples
Check if Any of Element in Column is True
In the following program, we take a DataFrame and check if any of its element in columns is True.
Example.py
import pandas as pd
data = {'col_0': [0, 0, 2, 4], 'col_1': [0, 0, 0, 0]}
df = pd.DataFrame(data)
result = df.any()
print(result)
Output
col_0 True
col_1 False
dtype: bool
Check if Any of Element in Row is True (axis=1)
In the following program, we take a DataFrame and check if any of its element in rows is True.
Pass axis=1 to any() method.
DataFrame
Example.py
import pandas as pd
data = {'col_0': [0, 0, 2, 4], 'col_1': [0, 0, 0, 0]}
df = pd.DataFrame(data)
result = df.any(axis=1)
print(result)
Output
0 False
1 False
2 True
3 True
dtype: bool
Do not Skip NA Values (skipna=False)
If we would like to consider NA values as True, then pass skipna=False
to any() method.
Example.py
import pandas as pd
import numpy as np
data = {'col_0': [0, 0, 0, 0], 'col_1': [np.nan, 0, 0, 0]}
df = pd.DataFrame(data)
result = df.any(skipna=False)
print(result)
Output
col_0 False
col_1 True
dtype: bool
np.nan is True if skipna=False.
Conclusion
In this Pandas Tutorial, we learned how to using pandas DataFrame.any() method.