How to check if any row in a Pandas DataFrame contains negative values ?

Published: April 13, 2023

Tags: Python; Pandas; Dataframe;

DMCA.com Protection Status

Create synthetic data

First, let's generate artificial data and use it to create a Pandas dataframe.

import pandas as pd
import numpy as np

np.random.seed(42)

data = np.random.uniform(low=-9.0, high=100.0, size=(10,4))

df = pd.DataFrame(data=data, columns=['A','B','C','D']).round(1)

print(df)

The code above will generate:

      A     B     C     D
0  31.8  94.6  70.8  56.3
1   8.0   8.0  -2.7  85.4
2  56.5  68.2  -6.8  96.7
3  81.7  14.1  10.8  11.0
4  24.2  48.2  38.1  22.7
5  57.7   6.2  22.8  30.9
6  40.7  76.6  12.8  47.1
7  55.6  -3.9  57.2   9.6
8  -1.9  94.4  96.3  79.1
9  24.2   1.6  65.6  39.0

Using any

Checking for negative values in a Pandas dataframe can be done using the any() method along the axis 1:

(df < 0).any(axis=1)

returns

0    False
1     True
2     True
3    False
4    False
5    False
6    False
7     True
8     True
9    False
dtype: bool

Using min()

Another way to achieve this task is by making use of the min() method.

df.min(axis=1)

returns

0    31.8
1    -2.7
2    -6.8
3    10.8
4    22.7
5     6.2
6    12.8
7    -3.9
8    -1.9
9     1.6
dtype: float64

References

Links Site
any() pandas.pydata.org
min() pandas.pydata.org