Multiple if in lambda python

I am trying to use 3 if statements within a python lambda function. Here is my code:

y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' '

I Have been able to get two if statements to work just fine e.g.

x=lambda cake: "Yum" if cake=="chocolate" else "Yuck"

Essentially, I want a lambda function to use if statements to return 'X' if the symbol is True, 'O' if it is false, and ' ' otherwise. I'm not even sure if this is even possible, but I haven't been able to find any information on the internet, so I would really appreciate any help :)

asked Oct 30, 2015 at 15:23

4

You are missing an else before 'O'. This works:

y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '

However, I think you should stick to Adam Smith's approach. I find that easier to read.

answered Oct 30, 2015 at 15:26

Cristian LupascuCristian Lupascu

37.7k15 gold badges95 silver badges135 bronze badges

0

You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get to symbolize your final "else"

y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ')

answered Oct 30, 2015 at 15:27

Adam SmithAdam Smith

49.5k11 gold badges70 silver badges108 bronze badges

2

This is one way where you can try multiple if else in lambda function

Example,

largest_num = lambda a,b,c : a if a>b and a>c else b if b>a and b>c else c if c>a and c>b else a

largest_num(3,8,14) will return 14

answered Aug 28, 2021 at 16:18

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 arguments: expression

An anonymous function which we can pass in instantly without defining a name or any thing like a full traditional function.

While we are using this lambda function we are limited with only one condition and an else condition. We cannot add multiple if statements like real python code. Now we can break those limitations and see how to add multiple if statements in the lambda function.

Creating Dataframe for demonestration:

Python3

import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',

                            'Krishna', 'Smith', 'Tessa'],

                   'Maths': [5, 3, 9, 10, 6, 3]})

print(df)

Output:

Name Maths 0 John 5 1 Jack 3 2 Shri 9 3 Krishna 10 4 Smith 6 5 Tessa 3

If you need to classify the students based on their marks as pass or fail it is pretty straightforward to perform with a lambda function. 

For example,

syntax: df[ ‘Result’ ] = df[ ‘Maths’ ].apply( lambda x: ‘Pass’ if x>=5 else ‘Fail’ )

Python3

import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',

                            'Krishna', 'Smith', 'Tessa'],

                   'Maths': [5, 3, 9, 10, 6, 3]})

df['Result'] = df['Maths'].apply(lambda x: 'Pass' if x>=5 else 'Fail')

print(df)

Output:

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

Adding Multiple If statements:

Now, To add multiple if statements to the lambda function we cannot add it directly in one line like the previous example. If we add more than one if statement or if we add an elif statement it will throw an error.

Python3

df['Maths_spl Class'] = df["maths"].apply(

  lambda x: "No Need" if x>=5 elif x==5 "Hold" else "Need")

Output:

df['Maths_spl Class'] = df["maths"].apply(lambda x: "No Need" if x>=5 elif x==5 "Hold" else "Need") ^ SyntaxError: invalid syntax

To solve this we can add the if statements to a traditional function and call the function with the apply() method in the dataframe.

syntax: def conditions():

               …conditions

In the following program, we are classifying the students according to the maths marks. We need to classify the students for the maths special class. Now we are going to classify the students with more than 8 points as “No need”, and the students less than 5 marks as “Need” and we are going to leave the rest of the student’s decisions on hold.

Python3

import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Jack', 'Shri',

                            'Krishna', 'Smith', 'Tessa'],

                   'Maths': [5, 3, 9, 10, 6, 3]})

def condition(x):

    if x>8:

        return "No need"

    elif x>=5 and x<=7:

        return "Hold decision"

    else:

        return 'Need'

df['Maths_Spl Class'] = df['Maths'].apply(condition)

print(df)

Output:

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

So as you can see we have successfully passed multiple if statements in the dataframe.


Can Python lambda have multiple statements?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.

How do you write if else in lambda Python?

Using if-else in lambda function Here, if block will be returned when the condition is true, and else block will be returned when the condition is false. Here, the lambda function will return statement1 when if the condition is true and return statement2 when if the condition is false.

Can I use if in lambda Python?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

How do you use nested if else in lambda?

You can have nested if else in lambda function. Following is the syntax of Python Lambda Function with if else inside another if else, meaning nested if else. value_1 is returned if condition_1 is true, else condition_2 is checked. value_2 is returned if condition_2 is true, else value_3 is returned.

Chủ đề