Understand the idea
str.contains returns a True/False mask telling you whether each string contains the requested text.
A small example
Searching for "a" with case=False matches "Ada" and "TEA"; a missing value gets False with na=False.
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
df[df["candy"].str.contains("a", case=False, na=False, regex=False)]What each part does
df["candy"].str.contains("a", ...)- Check each candy name for the text a; return one True/False flag per row.
case=False- Match A and a alike.
na=False- Treat a missing name as no match so the mask can filter rows.
regex=False- Treat the search text literally rather than as a pattern.
df[...]- Keep the rows whose flags are True.
Other choices for later exercises
~mask- Reverse the flags to select non-matches instead.
Your inputs
The editable setup on the right creates df. Run executes the setup and your work from top to bottom.
| candy | flavour | price | rating | shelf |
|---|---|---|---|---|
| Gummy Bear | fruity | 1.2 | 4.1 | A |
| Choco Pop | chocolate | 2.1 | 4.6 | B |
| Mint Bite | mint | 1.5 | 3.8 | A |
| Berry Loop | fruity | 2.8 | 4.4 | B |
| Cocoa Cube | chocolate | 3.4 | 4.9 | A |
| Lemon Drop | fruity | 1.8 | 4 | B |
Your task · Follow
- Using df, keep rows whose candy contains the letter "a", ignoring case.
- Return the filtered DataFrame.
- Use: str.contains().
Hint
regex=False makes the pattern literal; na=False keeps missing text out of the matches.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
df[df["candy"].str.contains("a", case=False, na=False, regex=False)]Optional stretch
Create a Series with ["A-12", "B-35", "C-8", "A-20"]. Try str.split("-").str[0] and str.extract(r"(\d+)").