Thursday, September 28, 2023

Python Tips - Lambda

  

Scenario

Lambda is a small anonymous function. It is typically used in another function. This feature provides engineers with great convenience and flexibility when apply some calculations to the data before it is processed by other functions. It is like we cook a meal, the flavors we add in will help us to get a rich taste. 

Here is a simple example.



This blog focuses on the usage of Lambda. How it is interpreted in Python, the behind-scene mechanism are out of scope. The point is, it is a type of function.

Let's check out some typical scenarios where Lambda is used. Noted Jupyter Lab is used for the demonstration.



Examples


In map

When we'd like to apply the same transformation to each element of a  list, using a lambda function in map() appears to be an effective way.




In sort as key

The example below shows how to sort an array by using a particular column.




In filter

What if we would like to pick out the elements from a list that meet some particular requirements? Lambda can get this done with grace.




In reduce

Reduce() is an interesting function, which brings the result of the current function to the next calculation as a parameter. Lambda, finds another place to show off. 




Combined with if-else condition

Incorporating if-else condition into Lambda obviously enables it to implement more complicated logics. In effect, we can embed another [if else] clause into [else] clause, in a recurrent manner, to handle even more complex conditions.




In DataFrame’s methods

DataFrame in Pandas comes with powerful data processing capabilities. Lambda is a great addition to help compose beautiful codes given its flexible nature.

Lambda in assign method:


Lambda in applymap method:


Lambda in apply method:



No comments:

Post a Comment

React - Makeover in React: W3Schools How To

When it comes to building a React app, I get used to searching for a UI library to build the front pages, a straightforward way to achieve f...