Home »
Python »
Python Programs
Check if string in one column is contained in string of another column in the same row
Given a pandas dataframe, we have to check if string in one column is contained in string of another column in the same row.
By Pranit Sharma Last updated : September 18, 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.
Problem statement
Suppose we are given a DataFrame that contains two columns A and B and we want to create a new column C out of A and B such that for the same row, if the string in column A is contained in the string of column B, then C = True and if not then C False.
Checking if string in one column is contained in string of another column in the same row
For this purpose, we will use df.apply() method inside which we will pass a lambda function for checking if the string matches with another string or not. The apply() method applies a function along an axis of the DataFrame.
Let us understand with the help of an example,
Python program to check if string in one column is contained in string of another column in the same row
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'A':['a','b','c','d','e'],
'B':['abc','kfd','kec','sde','akw']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Checking the string
df['C'] = df.apply(lambda x: x.A in x.B, axis=1)
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »