Creating User Defined Functions(UDFs) and Lambda Expressions
Sometimes Python built-in functions are not sufficient for the project we are working on. At these times we need to create a new function that will satisfy our needs: User Defined Functions(UDF). However sometimes we look for an easier and more flexible way than writing a loop, here are the Lambda Expressions. I will try to show how to use UDFs and Lambda Expressions with some simple examples.
Firstly, let’s create a loop that takes the first three letters of each element in the list and capitalize them.
months = ["January", "February", "March"]
for month in months:
print(month[:3].upper())Output:
JAN
FEB
MAR
We can turn this loop into a function:
def first_three_letter(list):
for i in list:
print(i[:3].upper())
Let’s call the function:
all_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
first_three_letter(all_months)Output:
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
Now I will try to use my user defined function on a Pandas series object.
import pandas as pd
ser=pd.Series(all_months)
first_three_letter(all_months)Output:
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
Here is the usage of user defined function on a DataFrame column.
df = pd.DataFrame({"MonthName": ["January", "February", "March"],
"MonthNumber": [1,2,3]})
first_three_letter(df["MonthName"])Output:
JAN
FEB
MAR
Lambda Expressions
I can do the same calculation in the user defined function by using lambda expressions. A lambda expression is a function defined without a name.
Usually, normal functions are defined with the ‘def’ keyword but anonymous functions are defined by using the lambda function. By the way, ‘Lambda Expression’ and ‘Anonymous Function’ mean the same thing. They can be used interchangeably. Lambda expressions can be used in many ways. I can name it and call with this name as shown with a clear example:
lambda_exp = lambda x: x[:3].upper()
lambda_exp("January")Output:
'JAN'
In order to use a lambda expression on a list, the map() function can come into play. This is another way of using lambda expressions. Map() is a built-in function that takes a function as a first argument and applies it to every element of its second argument, an iterable. This iterable can be list, string, series or tuple. Keep in mind that map() function returns an iterator, so you have to turn it into the intended format.
map_fnc = map(lambda_exp,all_months)
print(list(map_fnc))Output:
['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
Lambda expressions can take multiple inputs like other functions. Let’s create a function that calculates volume of right cylinders. We need to import pi number from math module. Lambda expression will take two arguments; one is height and the other is radius of the cylinder.
import math
math.pi
volume_of_cylinder = (lambda r,h: math.pi* (r**2) * h)
volume_of_cylinder(2,3)Output:
37.69911184307752
We can also use lambda expressions for filtering an iterable by using filter() function. Let’s filter a tuple that consists of radius and height knowledge of different cylinders. We want to see the values only if the volume of cylinder is less than 200. Firstly we will calculate all volumes and then filter them.
radius_height = [(2,3),(5,2),(4,7),(3,5),(6,4),(3,6),(4,3),(7,5),(9,4),(4,4),(5,5),(7,3)]
list(map(lambda x : (math.pi* (x[0]**2) * x[1]), radius_height))Output:
[37.69911184307752,
157.07963267948966,
351.85837720205683,
141.3716694115407,
452.3893421169302,
169.64600329384882,
150.79644737231007,
769.6902001294993,
1017.8760197630929,
201.06192982974676,
392.69908169872417,
461.81412007769956]
list(filter(lambda x : (math.pi* (x[0]**2) * x[1]) > 200, radius_height))Output:
[(4, 7), (6, 4), (7, 5), (9, 4), (4, 4), (5, 5), (7, 3)]
Use Lambda Expression as an anonymous function inside another function
Lambda expressions can be used inside another function. Let’s create a power function that takes two arguments a and n, where a is multiplied by itself n times.
def power(a,n):
return a**n
print(power(2,2))
print(power(2,3))Output:
4
8
To be able to create different functions from this power(a,n) function, a lambda expression can be used inside the function.
Lambda expression gives the flexibility to create different functions by changing the anonymous function.
def power(n):
return lambda a: a**n
power2=power(2)
power3=power(3)
print(power2(2))
print(power3(2))Output:
4
8
I tried to show you how to use ‘Lambda Expressions’ and ‘User Defined Functions’ with some simple examples. Thank you for reading.