Pandas dataframe str.contains() AND operation

Learn, how can we use pandas dataframe str.contains() method and AND operation?
Submitted by Pranit Sharma, on October 03, 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.

Problem statement

Suppose, we have a DataFrame with multiple columns and we need to apply the contains() method of string and also the AND operation. The contains() method will return that column that contains the specific value passed inside this method.

The AND operation is used as a logical operator, logically AND operator between two values is the product of two values which means if both the values are true then it means the condition is satisfied otherwise it is false.

Pandas dataframe str.contains() Method with AND operation

For this purpose, we will first create a DataFrame with a column containing some strings and then we will use contains() method with this column of DataFrame.

We will then use AND operator use & syntax and apply another contains() method on the same column.

Let us understand with the help of an example,

Python program for Pandas dataframe str.contains() AND operation

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d = {'col':['A boy',
            'A good boy',
            'A vergy good boy',
            'I am a very good boy']}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")

# Using contains and AND operation
res = df[(df['col'].str.contains('good')) & (df['col'].str.contains('am'))]

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Pandas dataframe str.contains() AND operation

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.