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

Rahul S
2 min readSep 8

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]

Python: iter, enumerate, zip

3 min read

Oct 9

Python: Exception Handling

3 min read

Oct 9

Python: remove() and pop()

3 min read

Oct 6

Python: update() method of dictionary

2 min read

Apr 16

Tail recusion and tail recursive elimination

2 min read

Apr 10

Python -1

1 min read

Apr 1

Python: Local, Nonlocal and Global variables

2 min read

Sep 27

Python: GIL (Global Interpreter Lock)

2 min read

Sep 27

Python: Deep and Shallow Copy

2 min read

Sep 25

Python: range(), numpy.arange(), and numpy.linspace()

3 min read

Sep 9

Rahul S

I learn as I write | LLM, NLP, Statistics, ML

Recommended from Medium

Lists

See more recommendations