在Pandas Lambda函数中使用Apply,有多个if语句
在这篇文章中,我们将看到如何在一个pandas数据框架中应用多个带有lambda函数的if语句。在现实世界中,有时我们需要在一个数据框架中应用多个条件语句,以便为更好地分析数据做准备。
我们通常使用lambda函数来应用数据框架上的任何条件。
语法: lambda参数:表达式
一个匿名函数,我们可以立即传入,而不需要定义名称或任何像完整的传统函数的东西。
当我们使用这个lambda函数时,我们只能使用一个条件和一个else条件。我们不能像真正的python代码那样添加多个if语句。现在我们可以打破这些限制,看看如何在lambda函数中添加多个if语句。
创建Demonestration的数据框架
# Importing the library
import pandas as pd
# dataframe
df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',
'Krishna', 'Smith', 'Tessa'],
'Maths': [5, 3, 9, 10, 6, 3]})
print(df)
输出:
Name Maths
0 John 5
1 Jack 3
2 Shri 9
3 Krishna 10
4 Smith 6
5 Tessa 3
如果你需要根据学生的分数将其分为合格或不合格,用lambda函数来执行是非常直接的。
例如,
语法: df[ ‘Result’ ] = df[ ‘Maths’ ].apply( lambda x: ‘Pass’ if x>=5 else ‘Fail’ )
# Import the library
import pandas as pd
# dataframe
df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',
'Krishna', 'Smith', 'Tessa'],
'Maths': [5, 3, 9, 10, 6, 3]})
# Adding the result column
df['Result'] = df['Maths'].apply(lambda x: 'Pass' if x>=5 else 'Fail')
print(df)
输出:
Name Maths Result
0 John 5 Pass
1 Jack 3 Fail
2 Shri 9 Pass
3 Krishna 10 Pass
4 Smith 6 Pass
5 Tessa 3 Fail
添加多个If语句
现在,要向lambda函数添加多个if语句,我们不能像前面的例子那样直接在一行中添加。如果我们添加一个以上的if语句,或者添加一个elif语句,就会出现错误。
df['Maths_spl Class'] = df["maths"].apply(
lambda x: "No Need" if x>=5 elif x==5 "Hold" else "Need")
输出:
df['Maths_spl Class'] = df["maths"].apply(lambda x: "No Need" if x>=5 elif x==5 "Hold" else "Need")
^
SyntaxError: invalid syntax
为了解决这个问题,我们可以将if语句添加到一个传统的函数中,并在数据框中用apply()方法调用该函数。
语法: def conditions():
…conditions
在下面的程序中,我们要根据数学分数对学生进行分类。我们需要对数学特长班的学生进行分类。现在我们要把8分以上的学生归为 “不需要”,5分以下的学生归为 “需要”,其余学生的决定则暂不考虑。
# Import the library
import pandas as pd
# dataframe
df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',
'Krishna', 'Smith', 'Tessa'],
'Maths': [5, 3, 9, 10, 6, 3]})
# Defining all the conditions inside a function
def condition(x):
if x>8:
return "No need"
elif x>=5 and x<=7:
return "Hold decision"
else:
return 'Need'
# Applying the conditions
df['Maths_Spl Class'] = df['Maths'].apply(condition)
print(df)
输出:
Name Maths Maths_Spl Class
0 John 5 Hold decision
1 Jack 3 Need
2 Shri 9 No need
3 Krishna 10 No need
4 Smith 6 Hold decision
5 Tessa 3 Need
所以你可以看到,我们已经成功地在数据框架中传递了多个if语句。