How to use the all() method in pandas
The all() function
The pandas all() function returns a single boolean value for each row or column. The function returns True if all the values in the given axis are true or False if any value is false.
Syntax
all(axis=0, bool_only=None, skipna=True, level=None)
Parameters
-
axis: This represents the index to perform the operation. The value0indicates rows while1indicates the columns. -
bool_only: This is an optional parameter that specifies whether or not to check for only boolean columns. The default value isNone. -
skipna: This is an optional parameter. The default isTrue. If set toFalse, it won’t skip null values. Instead, it will returnTruefor NaN values. -
level: This is an optional parameter. The default isNone. It specifies the level (in the case of multilevel) to count along.
Return type
It returns true or false for each row/column.
Example
The following code will demonstrate how to use the any() function in pandas:
import pandas as pdimport numpy as np# Create a DataFramedf = pd.DataFrame({'A': [1, np.nan, 0, 2, 0, np.nan, 4],'B': [1, 1, 3, 5, 0, 0, 5],'C': [np.nan, 0, np.nan, 0, 1, 0, 0]})# finds if value is true or not using all()print(df.all(axis=1))
Explanation
In the code above:
-
Lines 1–2: We import the needed libraries.
-
Lines 5–7: We create a DataFrame,
df, from a dictionary. -
Line 13: We use the
any()function to return aTruevalue if any value in the column axis is true. Otherwise,Falseis returned.