Python: filter(), map(), reduce(), and apply() functions

Rahul S
2 min readSep 8, 2023

1. Lambda Functions:

  • lambda arguments: expression - Create an anonymous inline function.
square = lambda x: x ** 2
result = square(5) # Result is 25

2. Filter Function:

  • filter(function, iterable) - Filter elements from an iterable based on a function.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4, 6]

3. Map Function:

  • map(function, iterable) - Apply a function to each element in an iterable and return a map object.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers)) # [1, 4, 9, 16, 25]

4. Reduce Function (functools):

  • functools.reduce(function, iterable, initializer=None) - Applies a binary function cumulatively to the items of an iterable, reducing them to a single value.
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
# Result is 120 (1*2*3*4*5)

5. Apply Function (Pandas):

In pandas, the apply() function is used to apply a function along the axis of a DataFrame or Series.

  • df.apply(func, axis=0) - Apply a function to each column (axis=0) or row (axis=1) of a DataFrame.
  • series.apply(func) - Apply a function to each element in a Series.

Example (DataFrame):

import pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
# Apply a custom function to each column

result = df.apply(lambda x: x * 2, axis=0)

# Resulting DataFrame:
# A B
# 0 2 8
# 1 4 10
# 2 6 12

Example (Series):

import pandas as pd

data = {'A': [1, 2, 3, 4, 5]}
series = pd.Series(data['A'])

# Apply a lambda function to each element
result = series.apply(lambda x: x ** 2)

# Resulting Series: [1, 4, 9, 16, 25]

--

--