Filter pandas DataFrame by substring criteria
Here is an example of how you can filter a pandas DataFrame by substring criteria:
Here is an example of how you can filter a pandas DataFrame by substring criteria:
Filter a pandas DataFrame by substring criteria
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'baz'], 'B': [1, 2, 3]})
# Define the substring you want to filter by
substring = 'ba'
# Use the `str.contains()` method to filter the DataFrame by substring
filtered_df = df[df['A'].str.contains(substring)]
print(filtered_df)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
This code creates a sample DataFrame with two columns ('A' and 'B') and three rows. It then defines a substring ('ba') that we want to filter the DataFrame by. The str.contains() method is used to check if the substring is contained within the values of the 'A' column. The resulting filtered DataFrame will only contain the rows where the substring is found in the 'A' column.