What is Python pandas any() and how does it work?
The DataFrame.any()
function from the Python library pandas is used to check if at least one value along a specified axis in a DataFrame evaluates to True
.
What is the syntax for pandas any()
?
The basic syntax of the pandas any()
function is straightforward. Here’s what it looks like:
DataFrame.any(axis=0, bool_only=None, skipna=True)
pythonThe pandas DataFrame.any()
function is similar to numpy.any()
in the popular Python library NumPy.
Important parameters for any()
The function accepts several parameters:
Parameter | Description | Default Value |
---|---|---|
axis
|
Specifies whether the method is applied along rows (0 or index) or columns (1 or columns) | 0 |
skipna
|
Specifies whether to skip NaN (Not a Number) values | True
|
bool_only
|
If True , only boolean columns will be considered
|
False
|
How to use pandas DataFrame.any()
Example 1: Checking for True
values in rows
The any()
function is most commonly used to check if any of the rows in a DataFrame contain at least one value that evaluates to True
. This can come in handy when validating conditions.
import pandas as pd
# Defining a DataFrame with three columns and three rows
data = {
'A': [0, 0, 0],
'B': [True, False, False],
'C': [False, False, False]
}
df = pd.DataFrame(data)
# Using the any() function to check if any values in the rows evaluate to True
result = df.any(axis=0)
print(result)
pythonIn the code above, pandas DataFrame.any()
returns a series showing that only column B contains a value that evaluates to True
. The output looks like this:
A False
B True
C False
dtype: bool
Example 2: Checking for True
values in columns
Similar to the first example, you can check if any column contains at least one True
value by passing axis=1
as a parameter:
result = df.any(axis=1)
print(result)
pythonThe output shows that only the first row has a value that evaluates to True
:
0 True
1 False
2 False
dtype: bool
Indexing in programming always starts at 0. That’s why a 0 is used to represent the first row in the output.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups