Applying Lambda functions to Pandas Dataframe
Last Updated :
09 Aug, 2024
In Python Pandas, we have the freedom to add different functions whenever needed like lambda function, sort function, etc. We can apply a lambda function to both the columns and rows of the Pandas data frame.
Syntax: lambda arguments: expression
An anonymous function which we can pass in instantly without defining a name or any thing like a full traditional function.
Applying Lambda Functions to Pandas
Below are some methods and ways by which we can apply lambda functions to Pandas:
- Dataframe.assign() on a Single Column
- Dataframe.assign() on Multiple Columns
- Dataframe.apply() on a Single Row
- Dataframe.apply() on Multiple Rows
- Lambda Function on Multiple Rows and Columns Simultaneously
Dataframe.assign() on a Single Column
In this example, we will apply the lambda function Dataframe.assign() to a single column. The function is applied to the ‘Total_Marks’ column, and a new column ‘Percentage’ is formed with its help.
Python
# importing pandas library
import pandas as pd
# creating and initializing a list
values= [['Rohan',455],['Elvish',250],['Deepak',495],
['Soni',400],['Radhika',350],['Vansh',450]]
# creating a pandas dataframe
df = pd.DataFrame(values,columns=['Name','Total_Marks'])
# Applying lambda function to find
# percentage of 'Total_Marks' column
# using df.assign()
df = df.assign(Percentage = lambda x: (x['Total_Marks'] /500 * 100))
# displaying the data frame
df
Output:

Dataframe.assign() on a Single Column
Dataframe.assign() on Multiple Columns
In this example, we will apply the lambda function Dataframe.assign() to multiple columns. The lambda function is applied to 3 columns i.e., ‘Field_1’, ‘Field_2’, and ‘Field_3’.
Python
# importing pandas library
import pandas as pd
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
[45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
[51, 2.3, 111]]
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'])
# Applying lambda function to find
# the product of 3 columns using
# df.assign()
df = df.assign(Product=lambda x: (x['Field_1'] * x['Field_2'] * x['Field_3']))
# printing dataframe
df
Output:

Dataframe.assign() on Multiple Columns
Dataframe.apply() on a Single Row
In this example, we will apply the lambda function Dataframe.apply() to single row. The lambda function is applied to a row starting with ‘d’ and hence square all values corresponding to it.
Python
# importing pandas and numpy libraries
import pandas as pd
import numpy as np
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
[45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
[51, 2.3, 111]]
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Apply function numpy.square() to square
# the values of one row only i.e. row
# with index name 'd'
df = df.apply(lambda x: np.square(x) if x.name == 'd' else x, axis=1)
# printing dataframe
df
Output:

Dataframe.apply() on a Single Row
Dataframe.apply() on Multiple Rows
In this example, we will apply the lambda function to multiple rows using Dataframe.apply(). The lambda function is applied to 3 rows starting with ‘a’, ‘e’, and ‘g’.
Python
# importing pandas and numpylibraries
import pandas as pd
import numpy as np
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
[45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
[51, 2.3, 111]]
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Apply function numpy.square() to square
# the values of 3 rows only i.e. with row
# index name 'a', 'e' and 'g' only
df = df.apply(lambda x: np.square(x) if x.name in [
'a', 'e', 'g'] else x, axis=1)
# printing dataframe
df
Output:

Dataframe.apply() on Multiple Rows
Lambda Function on Multiple Rows and Columns Simultaneously
In this example, we will apply the lambda function simultaneously to multiple columns and rows using dataframe.assign() and dataframe.apply().
Python
# importing pandas and numpylibraries
import pandas as pd
import numpy as np
# creating and initializing a nested list
values_list = [[1.5, 2.5, 10.0], [2.0, 4.5, 5.0], [2.5, 5.2, 8.0],
[4.5, 5.8, 4.8], [4.0, 6.3, 70], [4.1, 6.4, 9.0],
[5.1, 2.3, 11.1]]
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Apply function numpy.square() to square
# the values of 2 rows only i.e. with row
# index name 'b' and 'f' only
df = df.apply(lambda x: np.square(x) if x.name in ['b', 'f'] else x, axis=1)
# Applying lambda function to find product of 3 columns
# i.e 'Field_1', 'Field_2' and 'Field_3'
df = df.assign(Product=lambda x: (x['Field_1'] * x['Field_2'] * x['Field_3']))
# printing dataframe
df
Output

Lambda Function on Multiple Rows and Columns Simultaneously
Applying Lambda functions to Pandas Dataframe – FAQs
How Do You Apply Lambda to a DataFrame in Pandas?
In pandas, you can apply a lambda function to a DataFrame using the apply() function, which allows the lambda function to operate across columns or rows. Lambda functions provide a quick way of defining simple functions in one line without formally defining them using def.
Example of Applying Lambda to a DataFrame:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# Apply a lambda function to each element
df['A_plus_B'] = df.apply(lambda row: row['A'] + row['B'], axis=1)
print(df)
This adds a new column to the DataFrame that is the sum of columns ‘A’ and ‘B’.
How Do I Apply a Function to a Pandas DataFrame Column?
To apply a function to a column in a pandas DataFrame, you can use the apply() function on the DataFrame column. This is particularly useful for applying more complex operations across a column.
Example:
# Applying a function to modify each item in column 'A'
df['A_squared'] = df['A'].apply(lambda x: x ** 2)
print(df)
Is Pandas apply() Faster Than a For Loop?
Generally, pandas’ apply() function is faster than a for loop for operating on DataFrame columns or rows because apply() is optimized for pandas objects and can utilize internal optimizations. However, apply() might still be slower compared to vectorized operations which are the fastest way to operate on pandas DataFrames. Using apply() is faster than a for loop but slower than using vectorized operations directly supported by pandas or NumPy.
When Not to Use Lambda in Python?
Lambda functions are best used for simple, small functions. Situations where you should avoid using lambda functions include:
- Complex Functions: If the function is complex, using a standard function defined with
def is preferable for readability and maintainability. - Functions Requiring Multiple Expressions: Lambda functions are limited to a single expression.
- Functions That Require Documentation: Lambda functions do not support documentation via docstrings, so for functions that need clear documentation, use
def.
What is the Purpose of the apply() Function in Pandas?
The apply() function in pandas allows you to apply a function along an axis of the DataFrame or to elements of a Series. This makes it highly useful for:
- Applying transformations or computations that are more complex than what’s available through built-in methods.
- Reducing the dimensions of the data, thereby allowing for aggregation operations when used with a function that returns a single value.
- Applying user-defined or lambda functions across rows or columns efficiently.
Example of Aggregation Using apply():
result = df.apply(np.sum, axis=0) # Sum each column
print(result)
Please Login to comment...