Nest if .. elses:

lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)
Answer from Uriel on Stack Overflow
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 - Can I use multiple conditions in a pandas lambda if else statement? Absolutely! You can nest if statements within your lambda function to handle multiple conditions. How do I apply a lambda function to an entire DataFrame?
🌐
Data to Fish
datatofish.com › if-condition-in-pandas-dataframe
Two Ways to Apply an If-Condition on a pandas DataFrame
import pandas as pd data = {'fish': ['salmon', 'pufferfish', 'shark'], 'caught_count': [100, 5, 0] } df = pd.DataFrame(data) df['caught_count'] = df['fish'].apply(lambda x: 10 if x == "pufferfish") df['ge_100'] = df['caught_count'].apply(lambda x: True if x >= 100 else False)
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)
🌐
Towards Data Science
towardsdatascience.com › home › latest › 5 ways to apply if-else conditional statements in pandas
5 Ways to Apply If-Else Conditional Statements in Pandas | Towards Data Science
January 28, 2025 - df['new column name'] = df['column name'].apply(lambda x: 'value if condition is true' if x condition else 'value if condition is false')
🌐
ListenData
listendata.com › home › python
Python Lambda Function with Examples
Example 4 : Multiple or Nested IF-ELSE Statement Suppose you want to create a flag wherein it is yes when value of a variable is greater than or equal to 1 but less than or equal to 5. Else it is no if value is equal to 7. Otherwise missing. mydf = pd.DataFrame({'Names': np.arange(1,10,2)}) mydf["flag"] = mydf["Names"].apply(lambda x: "yes" if x>=1 and x<=5 else "no" if x==7 else np.nan)
🌐
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 - We are given a DataFrame and our ... it struggles with multiple if-elif-else logic. To overcome this, we can define a custom function and use apply() ......
Find elsewhere
🌐
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
I have a dataframe that looks like: A B C D SUM 2 5 -4 12 15 I try and run: df.apply((lambda x: x / x.sum() if x/x.sum() >= 0 else None), axis=1).fillna(0) to get, if cell is s...
🌐
Saturn Cloud
saturncloud.io › blog › how-to-use-ifelse-function-in-pandas-dataframe
How to Use If-Else Function in Pandas DataFrame | Saturn Cloud Blog
November 10, 2023 - To use the if-else function in Pandas DataFrame, you can use the apply() function along with a lambda function. The apply() function applies a function along an axis of the DataFrame.
🌐
GeeksforGeeks
geeksforgeeks.org › python › ways-to-apply-an-if-condition-in-pandas-dataframe
How to apply if condition in Pandas DataFrame - GeeksforGeeks
July 15, 2025 - Python · import pandas as pd # Sample DataFrame data = {'Name': ['John', 'Sophia', 'Daniel', 'Emma'], 'Experience': [5, 8, 3, 10]} df = pd.DataFrame(data) print("Original Dataset") display(df) # Apply if condition using lambda function df['Category'] = df['Experience'].apply(lambda x: 'Senior' if x >= 5 else 'Junior') print("Dataset with 'Senior'and 'Junior' Category") display(df) Output: Applying 'if condition' to classify the 'Experience' column into 'Senior' and 'Junior' categories ·
🌐
Statology
statology.org › home › pandas: how to use apply & lambda together
Pandas: How to Use Apply & Lambda Together
June 23, 2022 - The following code shows how to use apply and lambda to modifying an existing column in the DataFrame: #modify existing 'points' column df['points'] = df['points'].apply(lambda x: x/2 if x < 20 else x*2) #view updated DataFrame print(df) team points assists 0 A 9.0 5 1 B 44.0 7 2 C 9.5 7 3 D 7.0 9 4 E 7.0 12 5 F 5.5 9 6 G 40.0 9 7 H 56.0 4
🌐
IncludeHelp
includehelp.com › python › lambda-including-if-elif-and-else.aspx
Lambda including if, elif and else
September 24, 2023 - # Importing pandas package import pandas as pd # Creating a dictionary d = { 'One':[10,20,30,40], 'Two':[50,60,70,80] } # Creating a DataFrame df = pd.DataFrame(d,index=['a','b','c','d']) # Display original DataFrame print("Original DataFrame:\n",df,"\n") # Applying lambda function result = df['One'].apply(lambda x: x*10 if x<2 else (x**2 if x<4 else x+10)) # Display result print("Result:\n",result)
🌐
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.
🌐
Delft Stack
delftstack.com › home › howto › python pandas › pandas if else
How to Apply the If-Else Condition in a Pandas DataFrame | Delft Stack
February 2, 2024 - The x contains the marks in the lambda expression. We applied the if-else condition to the x and assigned the result accordingly in the Result column. ... # Python 3.x import pandas as pd import numpy as np df = pd.DataFrame( {"Name": ["Robert", "Sam", "Alia", "Jhon", "Smith"], "Marks": [60, 41, 79, 51, 88]} ) display(df) df["Result"] = df["Marks"].apply(lambda x: "Pass" if x >= 60 else "Fail") display(df)