-1

I'd like to check if a dataframe is empty or not. use ~df.empty return -2 while using Not df.empty return False.

why I cannot use ~?

df.empty
True

~df.empty
-2

not df.empty
False
roudan
  • 3,082
  • 5
  • 31
  • 72
  • 2
    `df.empty` returns a `bool` object. `~` is the *bitwise NOT* operator, so almost certainly not what you want. You want the *logical* not, `not`. This might be confusing because `pandas`/`numpy` overloads the bitwise logical operators to perform vectorized logical operations – juanpa.arrivillaga Nov 15 '21 at 19:41
  • 3
    Because it doesn't mean the same thing as `not`; otherwise there would be no need for it. – Scott Hunter Nov 15 '21 at 19:41

1 Answers1

3

In Python ~ is the bitwise not operator, it takes the bits and swaps 1s and 0s. For boolean values, true is 0b00000001 and false is 0b00000000 so ~true is 0b11111110 which, since bool a special case one byte int, evaluates as the signed integer value -2.

not on the other hand is the logical not operator, if a value is true/truthy it returns false, if a value is false/falsy it returns true, it doesn't care about the specific bits, only that (generally) at least one of the bits is 1.

Operation True
0b00000001
False
0b00000000
~ -2
0b11111110
-1
0b11111111
not False
0b00000000
True
0b00000001
Andrew
  • 1,544
  • 1
  • 18
  • 36
  • 2
    Probably an import point to make explicit, `bool` objects are instances of `int` because `bool` is a subclass of `int` – juanpa.arrivillaga Nov 15 '21 at 19:43
  • 1
    And more importantly, (most) operators behave *based on how their type tells them to behave*, so the what the tilde operator does depends on the types involved – juanpa.arrivillaga Nov 15 '21 at 19:44