liveBook · Manning

Str.contains

As explained in Pandas Workout: 200 exercises to make you a stronger data analyst

A pandas string-accessor method that tests each string value against a substring or regular expression and returns Boolean results.

`str.contains` searches each value in a pandas Series for a pattern and returns a Boolean Series with the same index. Treat the result as a row-by-row answer sheet: `True` marks values that match, and that Boolean Series can directly filter the original data. section 9.0 section 9.2

Table 9.1 What you need to know (view table figure)

Concept

What is it?

Example

To learn more

s.explode

Returns a new series with each element on its own line

s.explode()

http://mng.bz/RxDP

str.contains

Returns a series of booleans, indicating which elements of the input series contain the target string

s.str.contains('a')

http://mng.bz/2D2X

str.get_dummies

Returns a data frame containing 1s and 0s based on a categorical series

s['country']. get_dummies (sep=';')

http://mng.bz/1q2g

str.index

Returns a series of integers, each indicating where the target string was found in the corresponding element of the input series

s.str.index('a')

http://mng.bz/PzEP

str.len

Returns a series of integers indicating the length of each element

s.str.len()

http://mng.bz/Jg0v

str.replace

Returns a series based on an existing series, replacing the first argument with the second

s.str.replace('a', 'e')

http://mng.bz/wv6Q

str.split

Returns a series in which each element is a list of strings; the argument specifies the delimiter used to perform the split

s.str.split(';')

http://mng.bz/qrD2

str.strip

Returns a series of Python strings without the argument’s characters on either side

s.str.strip('.!?')

http://mng.bz/7D2y

s.isin

Returns a boolean series indicating whether a value in s is an element of the argument

s.isin(['A', 'B', 'C'])

http://mng.bz/mVW2

i.intersection

Returns a new index object containing elements in two existing index objects

i.intersection(i2)

http://mng.bz/5w21

Use this compact reference to place `str.contains` among related Series string operations: it tests whether each element contains a target string. section 9.0

Select respondents who reported Python

Survey language responses can contain several semicolon-separated values, such as `Python;JavaScript`. First remove missing `LanguageHaveWorkedWith` values, because applying `str.contains` to `NaN` causes an error. Then use the Boolean result to retain matching rows: `so_df = so_df.dropna(subset=['LanguageHaveWorkedWith'])` `so_df = so_df.loc[so_df['LanguageHaveWorkedWith'].str.contains('Python')]` This identifies respondents whose reported languages include `Python`, while leaving later analysis free to compare their experience distribution with another survey. section 8.2 section 8.2

The search pattern can be a regular expression, not merely literal text. For example, `[ae]` matches words containing either `a` or `e`. Be explicit with `regex=True` when regular-expression behavior is intended, rather than relying on a default that may change. section 9.0

Find capitalized words

A regular expression can describe the whole word, not just a substring. `^[A-Z]\w*$` matches a word that begins with an uppercase letter and continues through its end with zero or more alphanumeric characters. The anchors `^` and `$` make the test apply to the entire value, and `\w*` retains single-letter words such as `A` and `I`. `capitalized = s.str.contains('^[A-Z]\w*$', regex=True)` `words = s.loc[capitalized]` Clean punctuation first when quoted or punctuated words would otherwise hide an initial capital: `s.str.strip(string.punctuation).str.contains('^[A-Z]\w*$', regex=True)`. Apply that mask back to `s`, then use `count()` to total the selected words. section 9.2 section 9.2

Use the result as part of a broader filtering workflow:

  • Remove missing values in the searched column before testing it when missing entries would cause an error. section 8.2
  • Store or immediately use the Boolean Series as a mask with `.loc` to keep matching values or rows. section 9.0 section 9.2
  • Chain other string methods before searching when normalization matters, such as stripping punctuation before testing capitalization. section 9.2
  • Count selected values after filtering when the analytical question asks how many matches occur. section 9.2

How Pandas Workout: 200 exercises to make you a stronger data analyst covers it

How deep it goes
Explains Boolean-mask use, regular-expression patterns, punctuation cleanup, and explicit `regex=True`, without detailing matching internals.
Examples
Uses semicolon-separated programming-language survey responses and capitalized words from Alice in Wonderland.
What it assumes
Assumes familiarity with pandas Series and row filtering while demonstrating Boolean masks through concrete string searches.
What you can do after
Apply it via pandas to filter matching rows or values and count results with literal or regular-expression searches.
How it connects
Connects Boolean indexing, regular expressions, `dropna`, `loc`, `str.strip`, `count`, and pandas string accessors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pandas Workout: 200 exercises to make you a stronger data analyst. The section links point to the parts of the book it draws on.