Labs ICT
Pro Login

apply() & map()

Running custom functions on your data.

apply() & map()

Let me give you the power to transform data with custom functions. `apply()` and `map()` are your best friends when built-in methods aren't enough.

apply() with Lambda

The simplest way to apply a function to every value in a column:


import pandas as pd

data = {'Name': ['alice', 'bob', 'charlie'],
        'Age': [25, 30, 35]}
df = pd.DataFrame(data)

df['Name'] = df['Name'].apply(lambda x: x.title())
print(df)
    

The lambda function runs on every value. Think of it like a mini function you define right there. `x.title()` capitalizes the first letter of each name.

apply() with Custom Functions

For more complex logic, define a real function:


def age_group(age):
    if age < 30:
        return 'Young'
    else:
        return 'Senior'

df['Group'] = df['Age'].apply(age_group)
print(df)
    

This creates a new column based on conditions. It's like Excel's IF function, but way more flexible.

map() for Simple Mappings

When you just need to map values to other values:


grade_map = {'alice': 'A', 'bob': 'B', 'charlie': 'C'}
df['Grade'] = df['Name'].map(grade_map)
print(df)
    

Here is the thing — `map()` is simpler than `apply()` for basic lookups. Use it when you have a dictionary mapping old values to new ones.

Try it Yourself →

Key Takeaways

  • `apply()` applies a function to each value in a column
  • Lambdas are great for simple one-line transformations
  • Define functions for complex logic with conditions
  • `map()` is simpler for basic value-to-value mappings