Text cleaning
Normalize imported text fields by trimming whitespace and standardizing case.
Pandas · Pipe
Pandas' .str accessor supplies vectorized string operations for Series and Index objects, including DataFrame columns and labels. Use it for tasks such as trimming, changing case, matching patterns, splitting, extracting, and concatenating text.
The .str accessor exposes vectorized string operations for a pandas Series and can also be used with DataFrame column labels because df.columns is an Index. Accessor methods transform or inspect string elements while preserving pandas alignment and missing-value handling.
obj.str.<method>(...)A pandas Series, Index, or DataFrame depending on the selected object and operation; shape and values are determined by the specific .str method.
cat to combine string values according to its documented options.contains to produce elementwise boolean matches for a pattern or regular expression.rsplit when the meaningful delimiter is nearest the right-hand end of each value.import pandas as pd
df = pd.DataFrame({"name": [" Alice ", "Bob"]})
df["name"] = df["name"].str.strip().str.lower()
print(df)Cleans a string column by chaining the accessor's elementwise methods.
Normalize imported text fields by trimming whitespace and standardizing case.
Detect rows whose string values match or contain a pattern.
Split compound fields or extract structured parts into separate columns.
Clean DataFrame column labels before selecting or exporting data.
.str accessor?The .str accessor provides vectorized string operations on pandas Series and related Index objects. It lets code apply methods such as strip, lower, contains, and rsplit element by element without an explicit Python loop.
Follow-up: What happens when the data is not string-like? The accessor is intended primarily for strings, and unsupported non-string uses may fail or remain unsupported.
.str with a DataFrame?A DataFrame column is normally selected as a Series, so df["column"].str.method(...) applies a string operation to each value. The accessor can also operate on df.columns, because the columns object is an Index.
Follow-up: How can multiple transformations be composed? Chain accessor calls, such as .str.strip().str.lower(), when each stage returns compatible string-like data.
The accessor supports operations including concatenation, splitting, extraction, containment checks, and case or whitespace transformations. Methods that split or extract can change the result shape, for example by producing multiple columns or a DataFrame.
Follow-up: What should be checked when using regex-oriented methods? Verify whether the method interprets its pattern as a regular expression and choose arguments accordingly.
Series.strIndex.strSeries.str.extractallSeries.str.catSeries.str.containsSeries.str.rsplit