1

I often see the ~ operator used in pandas statements by people offering help on stackoverflow, but I can't think of any time where I've needed to use it because != just naturally comes to mind for me first. So I'm wondering why it exists.

For example, this statement:

(df['col_A'] > 100) & ~(df['col_A'] == 120)

... could just as easily be written as:

(df['col_A'] > 100) & (df['col_A'] != 120)

I imagine there must be situations where one must use ~, but what are they?

NaiveBae
  • 358
  • 1
  • 10
  • 4
    For example, when you use `isin`, it is the natural way to implemente a "not in" – 100tifiko Jun 09 '23 at 17:16
  • 3
    There's some good information [here](https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python), but the gist is that `~` is the unary complement operator, which is performing a mathematical operation, while the comparison `!=` is comparing the identities of the operands. – JRiggles Jun 09 '23 at 17:20

1 Answers1

3

Keeping things simple and easy to read is important, and that's a good reason to have equals = and not equals !=.

Being able to have a logical not ~ is important because it can be applied to many scenarios and clearly changes the equals to not equals in this case. Sometimes applying boolean logic can add complications and may require a better understanding of demorgans laws https://en.wikipedia.org/wiki/De_Morgan%27s_laws

Having more than one way to do this is okay since the two ways increase the flexibility and readiblity of the language.

michaelt
  • 56
  • 6