In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false
Answer from Zelazny7 on Stack Overflow
๐ŸŒ
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 - When you integrate lambda with if-else in pandas, you can effortlessly make conditional calculations in your DataFrame.
๐ŸŒ
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 6, 2023 - df['new column name'] = df['column name'].apply(lambda x: 'value if condition is true' if x condition else 'value if condition is false')
Discussions

python - Conditional Logic on Pandas DataFrame - Stack Overflow
maybe I don't know pandas, but it seems that you have two numbers in data -- which one are you checking against (seemingly the one on the right? What relevance is the number on the left?) ... You want to apply a function that conditionally returns a value based on the selected dataframe column. In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
pandas - Python lambda function if else condition - Stack Overflow
Question: Trying to understand someone else's code. Can someone please explain what the lambda function is doing here?. Does the lambda function here translates to: If the first 3 digits of OrderNu... More on stackoverflow.com
๐ŸŒ stackoverflow.com
If-else condition in assign statement in pipe chain with pandas?
You can still use np.where() inside the lambda >>> df.assign(some="value").assign(id=lambda df: np.where(df["country"] == "Switzerland", "CH", "EU")) country some id 0 Switzerland value CH 1 Poland value EU 2 Germany value EU If you modify the country column in the chain - you can see it's working on the current "piped" version of the data: >>> df.assign(country="should not match").assign(id=lambda df: np.where(df["country"] == "Switzerland", "CH", "EU")) country id 0 should not match EU 1 should not match EU 2 should not match EU Although you may want to choose a different variable name for the lambda - it can get confusing. There's also .map() which can be passed a dictionary - it's useful for multiple options: >>> df.assign(some="value").assign(id=lambda df: df["country"].map(dict(Switzerland="CH", Poland="PL")).fillna("EU")) country some id 0 Switzerland value CH 1 Poland value PL 2 Germany value EU More on reddit.com
๐ŸŒ r/learnpython
5
5
December 30, 2022
python - Lambda including if...elif...else - Stack Overflow
Nest if .. elses: lambda x: x*10 if x<2 else (x**2 if x<4 else x+10) More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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 - While the lambda function is good for simple conditions, it struggles with multiple if-elif-else logic. To overcome this, we can define a custom function and use apply() to handle more complex branching logic. For example, if we want to label scores above 8 as "No need", scores between 5 and 7 as "Hold decision", and below 5 as "Need", we canโ€™t do this with a single lambda expression directly. ... import pandas as pd df = pd.DataFrame({ 'name': ['John', 'Jack', 'Shri', 'Krishna', 'Smith', 'Tessa'], 'marks': [5, 3, 9, 10, 6, 3] }) print(df)
๐ŸŒ
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
May 1, 2026 - 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.
๐ŸŒ
ProjectPro
projectpro.io โ€บ blog โ€บ how to apply lambda functions to python pandas?
How To Apply Lambda Functions To Python Pandas?
October 28, 2024 - You can use Lambda functions in Pandas to apply conditional logic to data. This can be done by using nested if-else statements within the lambda function.
๐ŸŒ
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 - 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)
Find elsewhere
๐ŸŒ
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) That's it!
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71260517 โ€บ python-lambda-function-if-else-condition โ€บ 71260558
pandas - Python lambda function if else condition - Stack Overflow
Question: Trying to understand someone else's code. Can someone please explain what the lambda function is doing here?. Does the lambda function here translates to: If the first 3 digits of OrderNumber are not 486 and not 561, and the first digit is not 8 then set the column value data_df[OrderNumber] of the dataframe to empty string; otherwise leave it as it is? import sqlalchemy as sq import pandas as pd data_df = pd.read_csv('/dbfs/FileStore/tables/CustomerOrders.txt', sep=',', low_memory=False, quotechar='"', header='infer' , encoding='cp1252') data_df[OrderNumber] = data_df[OrderNumber].apply(lambda x: x if x[:3] != '486' and x[:3] != '561' and x[:1] != '8' else "") .............
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ if-else condition in assign statement in pipe chain with pandas?
r/learnpython on Reddit: If-else condition in assign statement in pipe chain with pandas?
December 30, 2022 -

Hello everyone,

I can't figure this one out, unfortunately: How do I use an if-else statement in the assign function from pandas to create a new column called 'id'? I know that I could do it alternatively with np.where at the beginning, like in the commented out line, but for future applications, I would like to know how to do it properly in the pipe chain. I tried a lambda function, but it throws the following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Help to solve this is much appreciated!

(data
    # .assign(country_indicator = np.where(data.country == "Switzerland", "CH", "EU"))
    .query("continent == 'Europe'")
    .reset_index(drop=True)
    .assign(id = lambda df: "CH" if df.country == "Switzerland" else "EU")
)

The data is the gapminder dataset and the relevant columns look like this:

index | country | continent
12	Albania	Europe
13	Albania	Europe
14	Albania	Europe
15	Albania	Europe
16	Albania	Europe
...	...	...
1603	United Kingdom	Europe
1604	United Kingdom	Europe
1605	United Kingdom	Europe
1606	United Kingdom	Europe
1607	United Kingdom	Europe
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
๐ŸŒ
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)
๐ŸŒ
HatchJS
hatchjs.com โ€บ home โ€บ how to use lambda functions with `if` and `else` statements in pandas
How to Use Lambda Functions with `if` and `else` Statements in Pandas
January 5, 2024 - A: You should use lambda if else in pandas when you need to write a conditional statement that is concise, flexible, and efficient. Lambda if else is a good choice for filtering data, applying functions, and performing other operations.
๐ŸŒ
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)
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)
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ top-methods-to-use-lambda-with-if-else-in-pandas
Top Methods to Use Lambda with If-Else in Pandas - sqlpey
November 23, 2024 - A: Yes, you can use nested if-else statements or logical operators to handle multiple conditions within a lambda function. For further reading on related topics, check out What is PostgreSQL , What is SQLAlchemy , and What is Pandas .
๐ŸŒ
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 - But we can achieve the same effect using if else & brackets i.e. lambda <args> : <return Value> if <condition > ( <return value > if <condition> else <return value>)