Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - check if dataframe has negative value in any column

Tags:

python

pandas

I wonder how to check if a pandas dataframe has negative value in 1 or more columns and return only boolean value (True or False). Can you please help?

In[1]: df = pd.DataFrame(np.random.randn(10, 3))

In[2]: df
Out[2]:
          0         1         2
0 -1.783811  0.736010  0.865427
1 -1.243160  0.255592  1.670268
2  0.820835  0.246249  0.288464
3 -0.923907 -0.199402  0.090250
4 -1.575614 -1.141441  0.689282
5 -1.051722  0.513397  1.471071
6  2.549089  0.977407  0.686614
7 -1.417064  0.181957  0.351824
8  0.643760  0.867286  1.166715
9 -0.316672 -0.647559  1.331545

Expected output:-

Out[3]: True
like image 257
hongkail Avatar asked Aug 07 '20 01:08

hongkail


People also ask

What does .ANY do in pandas?

Pandas DataFrame any() Method The any() method returns one value for each column, True if ANY value in that column is True, otherwise False. By specifying the column axis ( axis='columns' ), the all() method returns True if ANY value in that axis is True.


2 Answers

This does the trick:

(df < 0).any().any()

To break it down, (df < 0) gives a dataframe with boolean entries. Then the first .any() returns a series of booleans, testing within each column for the presence of a True value. And then, the second .any() asks whether this returned series itself contains any True value.

This returns a simple:

True
like image 164
billjoie Avatar answered Nov 03 '22 18:11

billjoie


You can chain two any

df.lt(0).any().any()
Out[96]: True
like image 20
BENY Avatar answered Nov 03 '22 17:11

BENY