how to use lambda function in python

Published on Aug. 22, 2023, 12:16 p.m.

In Python, a lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.

Here’s an example of a lambda function that takes one argument and returns the argument squared:

square = lambda x: x**2
result = square(5)
print(result)

This will output 25, which is 5 squared.

Lambda functions are often used as a quick and easy way to define small functions that are only used once. For example, you might use a lambda function when you need to pass a function as an argument to another function.

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)

This will output [1, 4, 9, 16, 25], which is a list of the squares of the numbers in the numbers list.

how to use lambda function in panda

Lambda functions are often used in pandas to apply a specific function to a column, row or element of a DataFrame or Series object.

Here’s an example of how to use a lambda function to add a new column to a DataFrame object:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['C'] = df['A'].apply(lambda x: x**2)
print(df)

This will output a DataFrame with three columns, A, B, and C, where C is the result of the lambda function that squares the values in column A.

You can also use a lambda function in conjunction with the apply() method to apply a specific function to a given axis of a DataFrame or a Series object. Here’s an example:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df['D'] = df.apply(lambda row: row['A'] + row['B'] + row['C'], axis=1)
print(df)

This will output a DataFrame with four columns, A, B, C, and D, where D is the result of the lambda function that sums the values in columns A, B, and C.

I hope that helps! Let me know if you have any additional questions or if you’d like more examples.

Tags: