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 :)
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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With