Select rows with positive/negative values in Pandas: df[df[col]>0/df[col]<0]

I have a pandas.DataFrame with the following data:

       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

I am trying to find the rows that have all elements with the same sign (either negative or positive). In the example above, that would be rows 1, 2, and 5.

I have read Pandas - Compare positive/negative values, but it doesn’t address the case where the values are negative.

I would appreciate any help.

You can use the apply method with a lambda function that checks if all elements in a row have the same sign. Here’s the solution:

import pandas as pd

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

same_sign_rows = df[df.apply(lambda row: all(row >= 0) or all(row < 0), axis=1)]

print(same_sign_rows)

This will output:

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