logo

The apply() Function

When built-in methods aren't enough, apply() runs your own function on each row or column.

Apply to a column:

df['length'] = df['name'].apply(len)

Apply a custom function:

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

df['category'] = df['age'].apply(categorize_age)

Apply across rows (access multiple columns):

df['full'] = df.apply(lambda row: f"{row['first']} {row['last']}", axis=1)

apply() is flexible but slower than vectorized operations. Use built-in methods when possible.

For custom transformations, see The Ultimate Pandas Bootcamp.