Now, we use this DataFrame to access only those rows with users that don’t contain the character 'A'.
Let’s apply the Tilde operator on the result: print(~df.str.contains('A')) The result is a DataFrame with Boolean values that indicate whether a user contains the character 'A' or not. Now apply the contains operation to find all user names that contain the character 'A'. This is the original DataFrame in the code: print(df) You can see this in action when printing the result of different operations: The tilde operator negates the Boolean values in the DataFrame: True becomes False and False becomes True. # Use Tilde to access all lines where user doesn't contain 'A' Here’s an example: import pandas as pdĭf = pd.DataFrame([, Sometimes, you’ll see the tilde operator in a Pandas DataFrame for indexing. You can see that this may lead to more intuitive indexing for some people.
#What operations are acceptable on python in visual studio code#
And here’s how the tilde operator comes into play: Use the tilde operator to transform your positive indices into negative indices as ~0=-1 and ~1=-2 and so on.Īnd here’s the code example: > lst = You may already know the negative indexing scheme in Python where you can access the last element of a Python list lst with lst and the second last element with lst.īut this may feel unnatural to you because negative array indexing starts with -1 and you’re used to positive indexing that starts with 0. You can use the tilde operator in Python when indexing list elements. So what’s the use of the Tilde operator? Tilde Python Array The general formula to calculate the tilde operation ~i is ~i=-i-1. Here’s a table showing the results of various tilde operations on negative integer values. Here’s a table showing the results of various tilde operations on positive integer values. If you struggle understanding how the tilde operator works on integers, have a look at the following table: Tilde Python Table Try it yourself in our interactive Python shell:Ĭan you guess the output of the code in the interactive shell? Guess first, then check if you guessed right! Have a look at the Python code where you convert the integer 42 with binary representation 0010 1010 to the complement -0010 1011: > a = 42 The general formula to calculate the tilde operation ~i on an integer value i is ~i=-i-1. For example, if you have the integer 0 represented by eight bits (one byte) 0000 0000, the tilde operation ~0000 0000 results in the value 1111 1111 which is the integer value -1. For example, the tilde operation ~1 becomes 0 and ~0 becomes 1 and ~101 becomes 010.īut you must be careful, because the integer value 0 is represented by many bits. What is the Tilde ~ in Python? Python’s Tilde ~n operator is the bitwise negation operator: it takes the number n as binary number and “flips” all bits 0 to 1 and 1 to 0 to obtain the complement binary number.