`apply` runs a function across pandas values, turning a repeated cleanup or calculation into one operation. Use it when built-in pandas methods do not express the rule you need: write a small Python function, apply it, and work with the returned object. section 9.2 section 5.16
Count a property of every value
To find the mean number of vowels per word, define `count_vowels(one_word)` to lowercase a word, count letters in `aeiou`, and return an integer. `s.apply(count_vowels)` produces a new Series of counts with the original word positions; chaining `.mean()` answers the aggregate question. section 9.2
The function determines what comes back. A function that returns an integer for each input produces numeric values that can be aggregated. A formatting function can instead return strings: after grouping compensation by employment and calculating means, `apply(lambda n: f'{n:,.2f}')` formats every nonmissing result for display. section 8.2 section 9.2
A practical workflow is:
- Inspect the values first, especially when many apparent categories signal inconsistent spelling or punctuation. section 5.16
- Encode the rule in a function that accepts one value and returns its cleaned or derived replacement. section 5.16 section 9.2
- Apply the function to the target Series or column, then measure whether the result improved the data or answers the question. section 5.16 section 9.2
For text columns, prefer pandas string operations when they already fit the task. The `str` accessor applies string methods across a Series and returns a new Series, making it useful for lowercasing, stripping punctuation, or matching regular expressions. Use `apply` when the operation is genuinely custom, such as a vowel-counting rule or a domain-specific standardization function. section 9.0 section 9.2 section 5.16
Normalize inconsistent labels
A Vehicle Make column with thousands of distinct names may contain case differences, punctuation, and alternate spellings. Create a function that capitalizes consistently, removes punctuation, and standardizes names you recognize; applying it to the column makes the cleanup rule explicit. Compare `value_counts()` or the number of distinct values before and after, then decide whether related columns such as street names need similar treatment. section 5.16


