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
🌐
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)
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-use-if-else-elif-in-python-lambda-functions
How to use if, else & 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.
🌐
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 - We could also use lambda to loop over a list and evaluate a condition · Let’s define a function with all the conditions that we want to evaluate · def f(grade): if grade > 7: return 'A+' elif grade >= 5 and grade <= 7: return 'A' elif grade <5: return 'B' else: return False ... DataFrames are a powerful tool for working with data in Python, and Pandas provides a number of ways to count duplicate rows in a DataFrame.
🌐
thisPointer
thispointer.com › home › functions › python : how to use if, else & elif in lambda functions
Python : How to use if, else & elif in Lambda Functions - thisPointer
April 30, 2023 - # Lambda function with if, elif & else i.e. # If the given value is less than 10 then Multiplies it by 2 # else if it's between 10 to 20 the multiplies it by 3 # else returns the unmodified same value converter = lambda x : x*2 if x < 10 else ...
🌐
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 ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python lambda using if else
Python Lambda using if else - Spark By {Examples}
May 31, 2024 - How to use an if else in Python lambda? You can use the if-else statement in a lambda as part of an expression. The lambda should have only one expression
🌐
AskPython
askpython.com › python › examples › lambda-with-if-else-conditions
Lambda With Conditional Statements in Python - AskPython
December 31, 2021 - 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
🌐
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
March 27, 2026 - 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))
🌐
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 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 ...
🌐
OpenGenus
iq.opengenus.org › python-lambda-if-else
Python lambda if else
November 27, 2022 - As an alternative, place a default value or NoneType in else part of the Lambda function in Python. The idea of using if else elif in Lambda is to add another if else part in the else part of the one line alternative of if else in Python.
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)
🌐
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
🌐
Eikke
eikke.com › python-ifelse-in-lambda › index.html
Python if/else in lambda – Ikke's blog
If you can use Python2.5 features, a “Conditional Expression” (http://docs.python.org/whatsnew/pep-308.html) is the just the right tool. f = lambda x: ‘big’ if x > 100 else ‘small’
🌐
GeeksforGeeks
geeksforgeeks.org › lambda-with-if-but-without-else-in-python
Lambda with if but without else in Python - GeeksforGeeks
October 6, 2021 - 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.