Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select rows with only positive or negative values in Pandas

I have the following DF:

df=pd.DataFrame({
                 'x':[1, 2, 3, -1, -2, -3],
                 'y':[-1, 3, 2, -4, 3, -2],
                 'z':[1 , 1, 5, 2, 1, -1]

}) or

       x  y  z
    0  1 -1  1
    1  2  3  1
    2  3  2  5
    3 -1 -4  2
    4 -2  3  1
    5 -3 -2 -1

The goal is to find the rows that all of their elements have the same (either negative or positive) values. In this example, it means selecting rows 1, 2, and 5.

I would appreciate any help. I am aware of this question: Pandas - Compare positive/negative values but it doesn't address the case where the values are negative.


Thank you :)

like image 949
Ali Avatar asked Jan 09 '20 22:01

Ali


Video Answer


1 Answers

You can use the OR (|) to combine conditions:

print(df[(df[df.columns] >= 0).all(axis=1) | (df[df.columns] <= 0).all(axis=1)])

Prints:

   x  y  z
1  2  3  1
2  3  2  5
5 -3 -2 -1

Or simpler:

print(df[(df >= 0).all(axis=1) | (df <= 0).all(axis=1)])

EDIT: As @Erfan stated in the comments, if you want strictly negative (without 0), you use <:

print(df[(df >= 0).all(axis=1) | (df < 0).all(axis=1)])
like image 159
Andrej Kesely Avatar answered Sep 22 '22 15:09

Andrej Kesely