apply vs Vectorised Operations

Python · Reshaping & Workflow

Theory

Vectorised operations work on whole columns at once in fast compiled code: df['amount'] * 1.18, df['a'] + df['b'], np.where(cond, x, y), .str and .dt methods. apply() calls a Python function once per value (Series.apply or Series.map) or once per row (df.apply(func, axis=1)), so it is flexible but runs at Python speed - often 100 times slower or worse on large data, and row-wise apply also loses column dtypes.

The rule: try the vectorised form first. A tax column is df['amount'] * 0.18, not apply(lambda x: x * 0.18). An if/else is np.where or np.select, not apply with if. A lookup is map(dict) or merge. Keep apply for logic with no vectorised equivalent, such as calling a parsing function from a library. For element-wise functions on a whole DataFrame, DataFrame.map(func) replaced applymap(), which is deprecated since pandas 2.1. groupby().apply is powerful but slow; prefer agg/transform where they fit.

Why we use it

Most slow pandas code comes from apply and loops where a vectorised expression exists. Knowing the vectorised alternatives keeps code short, fast and dtype-safe, while apply remains available for the truly custom cases.

When to use it

Use vectorised arithmetic, np.where/np.select, .str, .dt, map and merge first. Use Series.apply or map for a custom per-value function, df.apply(axis=1) only when the logic genuinely needs several columns and no vectorised form exists. Never loop with iterrows for calculations.

How it works

  1. Need a new value per row
  2. Plain arithmetic or comparison? Yes: Write it on columns: df['a'] * df['b']. No: Look further.
  3. if/else, text, date or lookup? Yes: np.where / .str / .dt / map / merge. No: Custom logic.
  4. Use Series.apply or map for a custom per-value function
  5. Use df.apply(axis=1) only if several columns are truly needed
  6. Fast, readable column

Syntax

df['c'] = df['a'] * df['b']                 # vectorised
df['c'] = np.where(df['a'] > 0, 'pos', 'neg')
s.map(func_or_dict); s.apply(func)
df.apply(func, axis=1)                      # row-wise, slow
df.map(func)                                # element-wise (was applymap)

Example

df['gst'] = df['amount'] * 0.18                    # fast
df['tier'] = np.where(df['amount'] > 1000, 'big', 'small')

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic