liveBook · Manning

Str.slice

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

Series.str.slice is a pandas string operation that extracts character ranges from each string value in a Series.

Use Series.str.slice to extract the same character range from every string in a pandas Series. The bounds follow Python slicing: start at the first index and stop before the end index, so 3,5 returns characters at indexes 3 and 4. section 5.4

Extracting months from dates

Suppose dateofdeath contains date strings with the month at indexes 5 and 6. Create a reusable month column with df['month'] = df['dateofdeath'].str.slice(5,7). The resulting Series retains the original row count and contains two-character month values. It can then become an index, be sorted, and support selection such as df.loc['02':'07', 'age']. section 5.6

s.str.slice(3,5)

See the concise Series string-accessor form: s.str.slice(3,5). section 5.4

Apply the operation when:

  • A column stores structured information inside strings and only a fixed character range is needed. section 5.4
  • The extracted substring becomes a cleaner working column while the larger original column can later be removed to reduce memory and computation. section 5.4

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

How deep it goes
Explains Python-style half-open bounds and demonstrates assignment, but stops short of alternative substring strategies.
Examples
Uses s.str.slice(3,5) and extracts month values from dateofdeath with df['dateofdeath'].str.slice(5,7).
What it assumes
Assumes familiarity with Python slicing and pandas Series, while reinforcing the string accessor syntax through examples.
What you can do after
Apply it via pandas to create substring columns for filtering, indexing, or simplifying string-heavy data.
How it connects
Connects string slicing with Python slicing, pandas Series, the string accessor, DataFrame columns, and index selection.

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.