0
0
Pandasdata~5 mins

apply() on columns in Pandas

Choose your learning style9 modes available
Introduction

We use apply() on columns to quickly change or analyze data in each column of a table.

You want to add 10 to every number in a column.
You need to check if values in a column are above a certain limit.
You want to convert all text in a column to uppercase.
You want to calculate the length of each string in a column.
You want to replace missing values in a column with a fixed number.
Syntax
Pandas
DataFrame['column_name'].apply(function)

The function can be a built-in function, a lambda (small anonymous function), or a custom function.

This applies the function to each value in the specified column.

Examples
Adds 1 to every value in the 'age' column.
Pandas
df['age'].apply(lambda x: x + 1)
Converts all names in the 'name' column to uppercase letters.
Pandas
df['name'].apply(str.upper)
Marks each score as 'Pass' or 'Fail' based on the value.
Pandas
df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail')
Sample Program

This code creates a small table with names, ages, and scores. Then it uses apply() on columns to change ages, names, and scores as explained.

Pandas
import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'score': [88, 45, 67]}
df = pd.DataFrame(data)

# Add 5 years to each age
new_ages = df['age'].apply(lambda x: x + 5)

# Convert names to uppercase
upper_names = df['name'].apply(str.upper)

# Mark scores as Pass or Fail
pass_fail = df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail')

print('New ages:')
print(new_ages)
print('\nUppercase names:')
print(upper_names)
print('\nPass or Fail:')
print(pass_fail)
OutputSuccess
Important Notes

If you want to change the column in the original table, assign the result back like df['age'] = df['age'].apply(...).

Using apply() is slower than vectorized operations but easier for custom logic.

Summary

apply() runs a function on each value in a column.

It helps change or analyze data quickly without loops.

You can use built-in, lambda, or your own functions with apply().