Reversal of string.contains in pandas

Given a pandas dataframe, we have to get a reverse result of string contains method.
Submitted by Pranit Sharma, on November 17, 2022

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.

Reversing the result of string.contains() method

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.

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.
pandas.

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 code 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:

Example: Reversal of string.contains in pandas

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.