All() And Any():Check Row Or Column Values For True In A Pandas DataFrame

Overview:

  • Pandas DataFrame has methods all() and any() to check whether all or any of the elements across an axis(i.e., row-wise or column-wise) is True.
  • all() does a logical AND operation on a row or column of a DataFrame and returns the resultant Boolean value.
  • any() does a logical OR operation on a row or column of a DataFrame and returns the resultant Boolean value.

 

Example – For DataFrame.all() method:

import pandas as pd

 

dataDict = {"v1":[True, True],

            "v2":[True, False],

            "v3":[True, True]};

dataFrame = pd.DataFrame(data=dataDict);

results = dataFrame.all(axis=0);

 

print("DataFrame:")

print(dataFrame)

 

print("Results:Computed column-wise")

print(results)

 

results = dataFrame.all(axis=1);

print("Results:Computed row-wise")

print(results)

 

Output:

DataFrame:

     v1     v2    v3

0  True   True  True

1  True  False  True

Results:Computed column-wise

v1     True

v2    False

v3     True

dtype: bool

Results:Computed row-wise

0     True

1    False

dtype: bool

 

 

Example – For DataFrame.any() method:

import pandas as pd

 

dataValues = {"Column1":[True, False, True],

              "Column2":[True, True, True],

              "Column3":[False, False, False]};

dataFrame = pd.DataFrame(data=dataValues);

resultData = dataFrame.any();

 

print("DataFrame");

print(dataFrame);

 

print("DataFrame:Computed column-wise");

print(resultData);

 

resultData = dataFrame.any(axis=1);

print("Result:Computed row-wise");

print(resultData);

 

Output:

DataFrame:

   Column1  Column2  Column3

0     True     True    False

1    False     True    False

2     True     True    False

DataFrame:Computed column-wise

Column1     True

Column2     True

Column3    False

dtype: bool

Result:Computed row-wise

0    True

1    True

2    True

dtype: bool


Copyright 2023 © pythontic.com