You can use str.contains()
on a pandas column and pass the substring as an argument to filter for rows containing the substring.
Pandas check if the string contains a substring
Simple example code.
Download CSV file
import pandas as pd
companies = pd.read_csv("companies.csv")
print(companies.shape)
# print(companies.head())
print(companies[companies.slogan.str.contains("secret")])
Output:
Source: https://realpython.com/python-string-contains-substring/
Pandas check if a row contains a string rather than an exact match
Use columns rather than rows when using pandas
df.your_col.str.contains("fox")
which will return an array of booleans, one bool for each row
Below you will get a dataframe where each row has a fox in your_col
column.
df[df.your_col.str.contains("fox")]
You can adjust the substring as needed to match your specific requirements. Additionally, you can set the case
parameter to False
if you want the search to be case-insensitive.
Do comment if you have any doubts or suggestions on this Python Pandas topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.