1

this will be my first query as I'm pretty new to understanding Python and its intricacies, especially all the symbols. In my attempt to understand the ~ (grave?) symbol I know it's related to binary output. However, I ran into this predicament in a Data Camp practice session. So here's my question: What is the "~" symbol doing in the second line of code?

apps is the dataframe, 'Rating' and 'Size' are columns

x: apps_with_size_and_rating_present = apps[(apps['Rating'].isnull()) & (apps['Size'].isnull())]
print(x)

This first line, x, does not have the ~ implemented and returns a blank seaborn plot in the terminal:

enter image description here

However, in the duplicate same line of code including the ~ it does not have the same issue:

y: apps_with_size_and_rating_present = apps[(~apps['Rating'].isnull()) & (~apps['Size'].isnull())]
print(y)

This second line, y, works as intended

enter image description here

How does the first line work but not the second? Is the isnull() the culprit or am I just not comprehending the functionality of the ~ symbol?

Any information would be appreciated!

I tried understanding the differences by running the same line of code with and without the ~ symbol but do not understand its purpose unless this is a compounded issue. What is the ~ symbol doing to the dataframe and why is it altering the graphical outputs?

danronmoon
  • 3,814
  • 5
  • 34
  • 56

1 Answers1

1

~x is implemented using the __invert__ method. For example, int.__invert__ swaps 0s for 1s and vice versa in the twos'-complement binary representation of an integer.

>>> ~8
-9
>>> ~-9
8

Other types can define __invert__ to mean something different. Many libraries use ~, &, and | as operators equivalent to not, and, and or (respectively). Since not x always means False if x else True, you have to pick another operator to implement you own kind of logical negation.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Are you saying the '~' symbol is interpreted as "not", as in we read for it to plot the apps['Rating' ,'Size'] as "plot this if it is not null?" I found out the graph does not function or display anything without the ~ symbol. – user20462606 Nov 09 '22 at 20:36