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
