The Wayback Machine - https://web.archive.org/web/20240915120401/https://www.geeksforgeeks.org/applying-lambda-functions-to-pandas-dataframe/
Open In App

Applying Lambda functions to Pandas Dataframe

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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.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 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

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

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)


Previous Article
Next Article

Similar Reads

Using Apply in Pandas Lambda functions with multiple if statements
In this article, we are going to see how to apply multiple if statements with lambda function in a pandas dataframe. Sometimes in the real world, we will need to apply more than one conditional statement to a dataframe to prepare the data for better analysis. We normally use lambda functions to apply any condition on a dataframe, Syntax: lambda arg
3 min read
Applying function to PySpark Dataframe Column
In this article, we're going to learn 'How we can apply a function to a PySpark DataFrame Column'. Apache Spark can be used in Python using PySpark Library. PySpark is an open-source Python library usually used for data analytics and data science. Pandas is powerful for data analysis but what makes PySpark more powerful is its capacity to handle bi
4 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Python Lambda Functions
Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. Python Lambda Function SyntaxSyntax: lambda arguments : expression This function can have any nu
9 min read
How to use if, else & elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions. Using if-else in lambda functionThe lambda function will return a value for every validat
2 min read
Conversion Functions in Pandas DataFrame
.numpy-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .numpy-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .numpy-table td:nth-child(odd) { background-color: #c6ebd9; } .numpy-table th { border: 1px solid #5fb962; text-align: left;
5 min read
How to apply functions in a Group in a Pandas DataFrame?
In this article, let's see how to apply functions in a group in a Pandas Dataframe. Steps to be followed for performing this task are - Import the necessary libraries.Set up the data as a Pandas DataFrame.Use apply function to find different statistical measures like Rolling Mean, Average, Sum, Maximum, and Minimum. You can use the lambda function
1 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
MoviePy – Applying Resize effect on Video Clip
In this article we will see how we can apply resize effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. We can resize the video with the help of resize method to resize the video clip, resize filter is the type of filter applied on it. In order to do thi
2 min read
MoviePy – Applying Color effect on Video Clip
In this article we will see how we can apply color effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Color effect is used to increase or decrease the color strength, when we lower the strength color looks more dark where as by increasing the strength i
2 min read
MoviePy – Applying Speed effect on Video Clip
In this article we will see how we can apply speed effect on the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Speed up video or slow down also known as fast motion/slow-motion effects in video production, which makes the video clips play faster or slower than o
2 min read
How to select the rows of a dataframe using the indices of another dataframe?
Prerequisites: PandasRandom Using Pandas module it is possible to select rows from a data frame using indices from another data frame. This article discusses that in detail. It is advised to implement all the codes in jupyter notebook for easy implementation. Approach:Import moduleCreate first data frame. In the example given below choice(), randin
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to Transform Spark DataFrame to Polars DataFrame?
Apache Spark and Polars are powerful data processing libraries that cater to different needs. Spark excels in distributed computing and is widely used for big data processing, while Polars, a newer library, is designed for fast, single-machine data processing, leveraging Rust for performance. Sometimes, you might want to transform a Spark DataFrame
3 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Lambda and filter in Python Examples
Prerequisite : Lambda in Python Given a list of numbers, find all numbers divisible by 13. Input : my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70] Output : [65, 39, 221] We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is witho
2 min read
Map function and Lambda expression in Python to replace characters
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read