By Hemanta Sundaray on 2021-08-13
We can test whether string elements of a Series contain a substring using the contains() method.
The contains() method returns a boolean Series.
Let’s read the budget.xlsx file into a DataFrame:
data = pd.read_excel("budget.xlsx")
data
Output:
We want to return all the rows where the string elements in the Profit column contain the string positive.
Note that the substring
positivethat we are trying to search for in theProfitcolumn might be in different cases. So, we will convert them to lowercase before applying thecontains()method.
condition = data["Profit"].str.lower().str.contains("positive")
condition
The contains() method returns a boolean Series.
Output:
Next, we pass the condition variable inside square brackets to return the required rows.
data[condition]
Output: