Pandas built-in vectorized operations are always the fastest approach. However, real-world business logic often requires custom branching (e.g. tax calculations, complex regex transformations, or calling external APIs). For these tasks, Pandas provides:
Series.map(): Map values of a Series using a dictionary or 1-to-1 function.Series.apply() / DataFrame.apply(): Apply arbitrary functions across a Series or along DataFrame axes.DataFrame.map() (formerly applymap in older Pandas): Apply a function element-wise across the entire table.Series.map() for Value SubstitutionSeries.apply() with Custom Functions & Lambdasaxis=1 so the lambda receives the row as a Series!apply()Unlike native vectorized methods (which run compiled in C), .apply() is effectively a Python-level loop under the hood.
Always prefer native vectorized math where possible:
df['Total'] = df['Price'] * df['Qty'] (Vectorized C speed)df['Total'] = df.apply(lambda r: r['Price'] * r['Qty'], axis=1) (Python loop speed)df.apply(custom_func, axis=1), what does the function receive as its argument?DataFrame.applymap() for applying a function element-wise to every cell in a DataFrame?df.apply(..., axis=1) for simple arithmetic operations like Col_A + Col_B?pd.Series(['delhi', 'mumbai']).apply(str.upper) return?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Handling Duplicates & Data Type Conversions | Vectorized String Methods (.str accessor) |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Combine 15 complete courses, 150 chapters, 541 topics, live SQL/Power BI/Tableau dashboards, and Scikit-Learn capstones at MSK Institute Shikohabad or Live Online.