Applying Lambda Functions to Pandas DataFrames
lambda
Functions solve various data science problems in Pandas python. We can DataFrame
apply lambda functions on rows and columns in pandas.
In this article, we will explore how to use lambda functions with pandas DataFrame
.
DataFrame
There are various applications of lambda functions on pandas such as filter()
, map()
and which 条件语句
we will explain with some examples in this article.
Lambda Function
A Lambda function consists of an expression.
Lambda
A function is a small function that can also be used as an anonymous function, which means it does not require any name. lambda
Functions are useful for solving small problems with less code.
DataFrame
The following syntax is used to apply lambda functions on pandas :
dataframe.apply(lambda x: x + 2)
Use DataFrame.assign()
the method to apply a Lambda function on a single column
dataframe.assign()
Method applies a Lambda function to a single column. Let's take an example.
In the following example, we Students Marks
have applied a lambda function on the column. After applying the Lambda function, the student percentage is calculated and stored in a new 百分比
column.
See the following implementation to DataFrame
apply a lambda function on a single column in Pandas.
Sample code:
import pandas as pd
# initialization of list
students_record = [
["Samreena", 900],
["Mehwish", 750],
["Asif", 895],
["Mirha", 800],
["Affan", 850],
["Raees", 950],
]
# pandas dataframe creation
dataframe = pd.DataFrame(students_record, columns=["Student Names", "Student Marks"])
# using Lambda function
dataframe1 = dataframe.assign(Percentage=lambda x: (x["Student Marks"] / 1000 * 100))
# display dataframe
print(dataframe1)
Output:
Student Names Student Marks Percentage
0 Samreena 900 90.0
1 Mehwish 750 75.0
2 Asif 895 89.5
3 Mirha 800 80.0
4 Affan 850 85.0
5 Raees 950 95.0
DataFrame.assign()
Apply Lambda functions on multiple columns using the
We can also apply Lambda functions to multiple columns using the method DataFrame
in Pandas.dataframe.assign()
For example, we have four columns Student Names
, Computer
, , Math
and Physics
. We apply a Lambda function on multiple subject columns such as Computer
, Math
, and to calculate the obtained scores stored in the column.Physics
Marks_Obtained
Implement the following example.
Sample code:
import pandas as pd
# nested list initialization
values_list = [
["Samreena", 85, 75, 100],
["Mehwish", 90, 75, 90],
["Asif", 95, 82, 80],
["Mirha", 75, 88, 68],
["Affan", 80, 63, 70],
["Raees", 91, 64, 90],
]
# pandas dataframe creation
df = pd.DataFrame(values_list, columns=["Student Names", "Computer", "Math", "Physics"])
# applying Lambda function
dataframe = df.assign(
Marks_Obtained=lambda x: (x["Computer"] + x["Math"] + x["Physics"])
)
# display dataframe
print(dataframe)
Output:
Student Names Computer Math Physics Marks_Obtained
0 Samreena 85 75 100 260
1 Mehwish 90 75 90 255
2 Asif 95 82 80 257
3 Mirha 75 88 68 231
4 Affan 80 63 70 213
5 Raees 91 64 90 245
Use DataFrame.apply()
the method to apply a Lambda function on a single line
dataframe.apply()
method applies a Lambda function to a single row.
For example, we applied the lambda function to a single row axis=1
. Using the lambda function, we increased each person's 月收入
value by 1000.
Sample code:
import pandas as pd
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"Names": ["Samreena", "Asif", "Mirha", "Affan", "Mahwish"],
"Age": [20, 25, 15, 10, 30],
"Monthly Income": [4000, 6000, 5000, 2000, 8000],
}
)
df["Monthly Income"] = df.apply(lambda x: x["Monthly Income"] + 1000, axis=1)
print(df)
Output:
ID Names Age Monthly Income
0 1 Samreena 20 5000
1 2 Asif 25 7000
2 3 Mirha 15 6000
3 4 Affan 10 3000
4 5 Mahwish 30 9000
Filtering data by applying a Lambda function
We can also filter the required data by applying Lambda functions.
filter()
The function takes a pandas Series and a lambda function. Lambda functions are applied to pandas Series returning specific results after filtering a given Series.
In the following example, we Age
have applied a lambda function on the column and filtered the age of people below 25 years old.
Sample code:
import pandas as pd
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"Names": ["Samreena", "Asif", "Mirha", "Affan", "Mahwish"],
"Age": [20, 25, 15, 10, 30],
"Monthly Income": [4000, 6000, 5000, 2000, 8000],
}
)
print(list(filter(lambda x: x < 25, df["Age"])))
Output:
[20, 15, 10]
Use map()
the function by applying a Lambda function
We can use map()
and lambda functions.
A lambda function is applied to a series to map the series based on the input correspondence. This function is useful to replace or substitute a series with other values.
When we use map()
the function, the input size will be equal to the output size. To understand map()
the concept of the function, see the following source code implementation.
Sample code:
import pandas as pd
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"Names": ["Samreena", "Asif", "Mirha", "Affan", "Mahwish"],
"Age": [20, 25, 15, 10, 30],
"Monthly Income": [4000, 6000, 5000, 2000, 8000],
}
)
df["Monthly Income"] = list(map(lambda x: int(x + x * 0.5), df["Monthly Income"]))
print(df)
Output:
ID Names Age Monthly Income
0 1 Samreena 20 6000
1 2 Asif 25 9000
2 3 Mirha 15 7500
3 4 Affan 10 3000
4 5 Mahwish 30 12000
By applying a Lambda function using if-else
the statement
We can also use lambda functions dataframes
to apply conditional statements on pandas.
In the following example, we have used conditional statements in lambda functions. We apply the condition to Monthly Income
the column.
If the monthly income is greater than or equal to 5000, Category
add it in the column Stable
; otherwise, add it UnStable
.
Sample code:
import pandas as pd
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"Names": ["Samreena", "Asif", "Mirha", "Affan", "Mahwish"],
"Age": [20, 25, 15, 10, 30],
"Monthly Income": [4000, 6000, 5000, 2000, 8000],
}
)
df["Category"] = df["Monthly Income"].apply(
lambda x: "Stable" if x >= 5000 else "UnStable"
)
print(df)
Output:
ID Names Age Monthly Income Category
0 1 Samreena 20 4000 UnStable
1 2 Asif 25 6000 Stable
2 3 Mirha 15 5000 Stable
3 4 Affan 10 2000 UnStable
4 5 Mahwish 30 8000 Stable
in conclusion
We have implemented DataFrame
various methods to apply Lambda functions on Pandas. We have seen how to apply lambda functions on rows and columns using dataframe.assign()
and methods.dataframe.apply()
We DataFrame
have demonstrated different applications of lambda functions on pandas series such as filter()
functions, map()
functions, conditional statements, etc.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Convert Tensor to NumPy array in Python
Publish Date:2025/05/03 Views:85 Category:Python
-
This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra
Saving NumPy arrays as images in Python
Publish Date:2025/05/03 Views:193 Category:Python
-
In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond
Transposing a 1D array in NumPy
Publish Date:2025/05/03 Views:98 Category:Python
-
Arrays and matrices form the core of this Python library. The transpose of these arrays and matrices plays a vital role in certain topics such as machine learning. In NumPy, it is easy to calculate the transpose of an array or a matrix. Tra
Find the first index of an element in a NumPy array
Publish Date:2025/05/03 Views:58 Category:Python
-
In this tutorial, we will discuss how to find the first index of an element in a numpy array. Use where() the function to find the first index of an element in a NumPy array The function in the numpy module where() is used to return an arra
Remove Nan values from NumPy array
Publish Date:2025/05/03 Views:118 Category:Python
-
This article discusses some built-in NumPy functions that you can use to remove nan values. Remove Nan values using logical_not() and methods in NumPy isnan() logical_not() is used to apply logical NOT to the elements of an array. isn
Normalizing a vector in Python
Publish Date:2025/05/03 Views:51 Category:Python
-
A common concept in the field of machine learning is to normalize a vector or dataset before passing it to the algorithm. When we talk about normalizing a vector, we say that its vector magnitude is 1, being a unit vector. In this tutorial,
Calculating Euclidean distance in Python
Publish Date:2025/05/03 Views:128 Category:Python
-
In the world of mathematics, the shortest distance between two points in any dimension is called the Euclidean distance. It is the square root of the sum of the squares of the differences between the two points. In Python, the numpy, scipy
Element-wise division in Python NumPy
Publish Date:2025/05/03 Views:199 Category:Python
-
This tutorial shows you how to perform element-wise division on NumPy arrays in Python. NumPy Element-Wise Division using numpy.divide() the function If we have two arrays and want to divide each element of the first array with each element
Convert 3D array to 2D array in Python
Publish Date:2025/05/03 Views:79 Category:Python
-
In this tutorial, we will discuss the methods to convert 3D array to 2D array in Python. numpy.reshape() Convert 3D array to 2D array using function in Python [ numpy.reshape() Function](numpy.reshape - NumPy v1.20 manual)Changes the shape