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.

Answer from Cristian Lupascu on Stack Overflow
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python lambda using if else
Python Lambda using if else - Spark By {Examples}
May 31, 2024 - The lambda should have only one expression so here, it should be if-else. The if returns the body when the condition is satisfied, and the else body is returned when the condition is not satisfied.
Discussions

Is there a way to perform "if" in python's lambda? - Stack Overflow
In Python 2.6, I want to do: f = lambda x: if x==2 print x else raise Exception() f(2) #should print "2" f(3) #should throw an exception This clearly isn't the syntax. Is it possible to More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Lambda including if...elif...else - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Implementing if-else in python dataframe using lambda when there are multiple variables - Stack Overflow
I am trying to implement if-elif or if-else logic in python while working on a dataframe. I am struggling when working with more than one column. ... If my if-else logic is based on only one column - I know how to do it. df['one'] = df["one"].apply(lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)) More on stackoverflow.com
๐ŸŒ stackoverflow.com
pandas - Lambda function with if else clause with Python - Stack Overflow
1 lambda function with multiple ifs using pandas df ยท 4 Implementing if-else in python dataframe using lambda when there are multiple variables More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-use-if-else-elif-in-python-lambda-functions
How to use if, else &amp; elif in Python Lambda Functions - GeeksforGeeks
July 23, 2025 - The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-use-if-else-amp-elif-in-python-lambda-functions
How to use if, else & elif in Python Lambda Functions
6 days ago - get_grade = lambda score: "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F" print(get_grade(95)) print(get_grade(85)) print(get_grade(75)) print(get_grade(65)) print(get_grade(45))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ using-apply-in-pandas-lambda-functions-with-multiple-if-statements
Using Apply in Pandas Lambda functions with multiple if statements - GeeksforGeeks
June 20, 2025 - import pandas as pd 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)
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ lambda with conditional statements in python
Lambda With Conditional Statements in Python - AskPython
October 6, 2023 - We create a lambda object as conditional_lambda. Then, we store a variable x and expression as x/100 from and in joining with that our conditional statement lies. The statement says that if x is less than 20 divide it by 100 else print it as it is.
Find elsewhere
๐ŸŒ
Kanoki
kanoki.org โ€บ 2022 โ€บ 09 โ€บ 12 โ€บ python-lambda-if-else-elif-with-multiple-conditions-and-filter-list-with-conditions-in-lambda
python lambda if, else & elif with multiple conditions and filter list with conditions in lambda | kanoki
September 12, 2022 - Without else does not work because it does not specify what to return if not x>7 ... Filtering lists with lambda will return all the elements of the list that return True for the lambda function ... The conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True ยท list(filter(lambda x: (x%2==0)&(x>=5), data)) Out: [10] In this case the only item in list that satisfied the condition is returned
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-lambda-if-else
Python Lambda - If Else, Nested If Else
In the following example program, we will write a lambda function that returns the number as is if divisible by 10, square of number if number is even, else cube of the number. x = lambda n: n if n == 0 else ( n**2 if n%2 == 0 else n**3 ) print(x(4)) print(x(3)) print(x(10)) ... Summarizing ...
Top answer
1 of 4
225

Nest if .. elses:

lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)
2 of 4
50

I do not recommend the use of apply here: it should be avoided if there are better alternatives.

For example, if you are performing the following operation on a Series:

if cond1:
    exp1
elif cond2:
    exp2
else:
    exp3

This is usually a good use case for np.where or np.select.


numpy.where

The if else chain above can be written using

np.where(cond1, exp1, np.where(cond2, exp2, ...))

np.where allows nesting. With one level of nesting, your problem can be solved with,

df['three'] = (
    np.where(
        df['one'] < 2, 
        df['one'] * 10, 
        np.where(df['one'] < 4, df['one'] ** 2, df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

numpy.select

Allows for flexible syntax and is easily extensible. It follows the form,

np.select([cond1, cond2, ...], [exp1, exp2, ...])

Or, in this case,

np.select([cond1, cond2], [exp1, exp2], default=exp3)

df['three'] = (
    np.select(
        condlist=[df['one'] < 2, df['one'] < 4], 
        choicelist=[df['one'] * 10, df['one'] ** 2], 
        default=df['one'] + 10))
df

   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

and/or (similar to the if/else)

Similar to if-else, requires the lambda:

df['three'] = df["one"].apply(
    lambda x: (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) 

df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15

List Comprehension

Loopy solution that is still faster than apply.

df['three'] = [x*10 if x<2 else (x**2 if x<4 else x+10) for x in df['one']]
# df['three'] = [
#    (x < 2 and x * 10) or (x < 4 and x ** 2) or x + 10) for x in df['one']
# ]
df
   one  two  three
0    1    6     10
1    2    7      4
2    3    8      9
3    4    9     14
4    5   10     15
๐ŸŒ
Medium
medium.com โ€บ @whyamit101 โ€บ using-pandas-lambda-if-else-0d8368b70459
Using pandas lambda if else. The biggest lie in data science? Thatโ€ฆ | by why amit | Medium
April 12, 2025 - You can nest if statements within your lambda function to handle multiple conditions. How do I apply a lambda function to an entire DataFrame? You can use the .apply() method combined with your lambda function to apply it to an entire DataFrame ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python lambda if
if...else in Lambda Function Python | Delft Stack
February 25, 2025 - Hereโ€™s how you can implement this: nested_if_lambda = lambda x: "Positive" if x > 0 else ("Negative" if x < 0 else "Zero") result1 = nested_if_lambda(10) result2 = nested_if_lambda(-5) result3 = nested_if_lambda(0) print(result1) print(result2) ...
Top answer
1 of 2
6

Apply across columns

Use pd.DataFrame.apply instead of pd.Series.apply and specify axis=1:

df['one'] = df.apply(lambda row: row['one']*100 if row['two']>8 else \
                     (row['one']*1 if row['two']<8 else row['one']**2), axis=1)

Unreadable? Yes, I agree. Let's try again but this time rewrite as a named function.

Using a function

Note lambda is just an anonymous function. We can define a function explicitly and use it with pd.DataFrame.apply:

def calc(row):
    if row['two'] > 8:
        return row['one'] * 100
    elif row['two'] < 8:
        return row['one']
    else:
        return row['one']**2

df['one'] = df.apply(calc, axis=1)

Readable? Yes. But this isn't vectorised. We're looping through each row one at at at time. We might as well have used a list. Pandas isn't just for clever table formatting, you can use it for vectorised calculations using arrays in contiguous memory blocks. So let's try one more time.

Vectorised calculations

Using numpy.where:

df['one'] = np.where(row['two'] > 8, row['one'] * 100,
                     np.where(row['two'] < 8, row['one'],
                              row['one']**2))

There we go. Readable and efficient. We have effectively vectorised our if / else statements. Does this mean that we are doing more calculations than necessary? Yes! But this is more than offset by the way in which we are performing the calculations, i.e. with well-defined blocks of memory rather than pointers. You will find an order of magnitude performance improvement.

Another example

Well, we can just use numpy.where again.

df['one'] = np.where(df['name'].isin(['a', 'b']), 100, df['two'])
2 of 2
1

you can do

df.apply(lambda x: x["one"] + x["two"], axis=1)

but i don't think that such a long lambda as lambda x: x["one"]*100 if x["two"]>8 else (x["one"]*1 if x["two"]<8 else x["one"]**2) is very pythonic. apply takes any callback:

def my_callback(x):
    if x["two"] > 8:
        return x["one"]*100
    elif x["two"] < 8:
        return x["one"]
    else:
        return x["one"]**2

df.apply(my_callback, axis=1)
๐ŸŒ
Iditect
iditect.com โ€บ programming โ€บ python-example โ€บ using-apply-in-pandas-lambda-functions-with-multiple-if-statements.html
Using Apply in Pandas Lambda functions with multiple if statements
import pandas as pd # Sample DataFrame df = pd.DataFrame({'A': [3, 7, 12, 5, 15]}) # Using apply with lambda and multiple if-else df['B'] = df['A'].apply(lambda x: "high" if x > 10 else ("medium" if 5 <= x <= 10 else "low")) print(df)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51789766 โ€บ lambda-function-with-if-else-clause-with-python
pandas - Lambda function with if else clause with Python - Stack Overflow
df2 = df.copy() for col in df.columns[:-1]: df2[col] = df.iloc[:, :-1].apply(lambda x: x[col] / x.sum() if x[col]/x.sum() >= 0 \ else None, axis=1).fillna(0) print(df2) A B C D SUM 0 0.133333 0.333333 0 0.8 15
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ lambda-with-if-but-without-else-in-python
Lambda with if but without else in Python - GeeksforGeeks
October 6, 2021 - Syntax: lambda variable : expression Where, variable is used in the exp ... Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ lambda-expression-python
Python Lambda Expressions Explained with Examples | DigitalOcean
July 8, 2025 - For instance, letโ€™s say you have a list of students with their grades and you want to categorize them based on their performance. You can use a conditional lambda function to create a categorization function that assigns a category based on the grade. categorize_student = lambda grade: 'Distinction' if grade >= 90 else 'Merit' if grade >= 80 else 'Pass' if grade >= 70 else 'Fail' students = [ {'name': 'Alice', 'grade': 95}, {'name': 'Bob', 'grade': 75}, {'name': 'Charlie', 'grade': 60}, {'name': 'David', 'grade': 85} ] for student in students: print(f"{student['name']}: {categorize_student(student['grade'])}")
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-lambda-if-condition
Python Lambda with If Condition: A Comprehensive Guide - CodeRivers
April 13, 2025 - This lambda function has multiple nested if - else conditions to assign a grade based on the student's score. The map() function in Python applies a given function to all items in an iterable. When used with a lambda function containing an if condition, it can transform elements based on a ...
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-38150.html
Compound if else statement
September 8, 2022 - I am using the following statement in my program df2['machine_status'] = df2['machine_status'].map( lambda x: 0 if x == 'NORMAL' else 1 )This clearly refers to the machine status in the program. I am changing the values normal and broken...