How to search for \”does-not-contain\” on a dataFrame in pandas

In this tutorial, you are going to learn how to search for rows in pandas dataFrame that do not contain a specific value in Python. You can use boolean indexing with the neagation(~) operator.

along with the negation(~) operator you can also use str.contains method

You can use str.contains() method to filter rows in a dataFrame where a column does not contain a specific value.

search for \”does-not-contain\” on a dataFrame in pandas

 

Steps:

Import Pandas : 

First of all, Install pandas and make sure to import it

Create a DataFrame:

Create a DataFrame with some values to demonstrate an example for better understanding

Use str.contains() along with the (~) operator :

str.contains() method is used to find the rows that contain the value and then negate it to get the rows that do not contain the value

 

#importing pandas as pd
import pandas as pd

#a Dataframe with sample values as fruits
data = {
        'A' = ['apple','banana','grape','pineapple','blueberry'],
        'B' = ['fruit','fruit','fruit','fruit','fruit']
}

df = pd.DataFrame(data)

#search for rows in column 'A' that do not contain the substring 'apple'
result = df[~df['A'].str.contains('apple')]

#printing the result
print(result)


output:

       A           B

1     banana        fruit

2     grape         fruit

3     blueberry     fruit

 

These [banana,grape,blueberry] are the only values that do not contain the substring ‘apple’ in them, so they are printed along with the values in column B and Yield the above output

Here the line :

df['A'].str.contains('apple')

this piece of code will identify which rows in column ‘A’ will contain the substring ‘apple’

If we negate this line of code

~df['A'].str.contains('apple')

This negation operator will find the rows that do not contain the substring ‘apple’.

 

Finally, This is how we search for “does-not-contain” on a dataframe in pandas

Hope this tutorial helps.

Leave a Reply

Your email address will not be published. Required fields are marked *