Home »
Python »
Python Programs
Reversal of string.contains in pandas
Given a pandas dataframe, we have to get a reverse result of string contains method.
By Pranit Sharma Last updated : October 05, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.
Reversing the result of string.contains() method
The string.contains() method is used to check whether a specific string or substring is present in a series/list or any other collection or string itself. If we apply this method on a column of a DataFrame then it returns n Boolean values where n is the number of elements of that column.
We need to find the reverse or opposite result of this method and hence we will simply use the tilde (~) sign in just before this method.
The tilde sign (~) in pandas is used when we work with Boolean values. In programming, we sometimes use some specific values that only have two values, either True or False. These values are known as Boolean values.
This tilde sign works as a negation operator that means is used to reverse the Boolean values.
Let us understand with the help of an example,
Python program to get a reverse result of string.contains() method
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d= {"A": ["Hello", "this", "is", "an", "article", "of", "includehelp"]}
# Creating DataFrame
df = pd.DataFrame(d)
# Display dataframe
print('Original DataFrame:\n',df,'\n')
# First getting actual result of contains method
res = df.A.str.contains("Hello|includehelo")
# Display actual results
print("Actual Results:\n",res,"\n")
# Display reverse results
print("Reversed Results:\n",~df.A.str.contains("Hello|includehelo"))
Output
The output of the above program is:
Python Pandas Programs »