AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
DashboardpandasApplying Functions to Columns
pandasNot Started

Applying Functions to Columns

Transform data column by column using apply, map, and vectorized operations

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

There are several ways to apply a function to DataFrame data:

Vectorized operations (fastest — always prefer these):

python df['salary_usd'] = df['salary_eur'] * 1.08 df['full_name'] = df['first'] + ' ' + df['last']

map() — element-wise on a Series:

python df['grade'].map({'A': 4.0, 'B': 3.0, 'C': 2.0}) # value substitution df['name'].map(str.upper)

apply() — row or column wise:

python # On a column (Series) df['age'].apply(lambda x: 'senior' if x >= 65 else 'other') # On entire rows (axis=1) df.apply(lambda row: row['first'] + ' ' + row['last'], axis=1)

When to use what:

  • 1. Vectorized arithmetic/string ops → always first choice (fastest)
  • 2. map() → replacing values, simple element transformations
  • 3. apply() → complex logic requiring access to the full row or custom functions
  • 4. Never use apply() when a vectorized operation exists

Examples

Categorizing ages

apply() is ideal when you need custom logic per element

import pandas as pd

df = pd.DataFrame({'name':['Alice','Bob','Carol','Dave'],'age':[17,25,68,42]})

def age_group(age):
    if age < 18: return 'minor'
    elif age < 65: return 'adult'
    else: return 'senior'

df['group'] = df['age'].apply(age_group)
print(df)
#     name  age   group
# 0  Alice   17   minor
# 1    Bob   25   adult
# 2  Carol   68  senior
# 3   Dave   42   adult

How well did you understand this?