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
๐ŸŒ
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 create a simple DataFrame with student names and their marks. This will be used to classify students using custom logic. Lambda functions in apply() are ideal for simple conditions such as pass/fail classification. ... 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)
Discussions

python - Using lambda if condition on different columns in Pandas dataframe - Stack Overflow
See similar questions with these tags. ... 0 Using lambda IF condition on columns in Pandas to extract and replace strings from a data frame comparing to a list More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Using Apply in Pandas Lambda functions with multiple if statements - Stack Overflow
I'm trying to infer a classification according to the size of a person in a dataframe like this one: Size 1 80000 2 8000000 3 8000000000 ... I want it to look like this: S... 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
Lambda if statement
You may be better just writing a normal function if it gets too complicated to understand, but for the sake of learning: something['SomeVariable'].apply(lambda x: dosomething() if isinstance(x, str) else dosomethingelse()) More on reddit.com
๐ŸŒ r/learnpython
9
6
August 18, 2015
๐ŸŒ
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)
๐ŸŒ
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?
๐ŸŒ
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.
๐ŸŒ
Statology
statology.org โ€บ home โ€บ pandas: how to use apply & lambda together
Pandas: How to Use Apply & Lambda Together
June 23, 2022 - You can use the following basic syntax to apply a lambda function to a pandas DataFrame: df['col'] = df['col'].apply(lambda x: 'value1' if x < 20 else 'value2') The following examples show how to use this syntax in practice with the following pandas DataFrame:
Find elsewhere
๐ŸŒ
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)
๐ŸŒ
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') For our specific example, the code would look like this: df['visits_category'] = df['visits_30days'].a...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71260517 โ€บ python-lambda-function-if-else-condition โ€บ 71260558
pandas - Python lambda function if else condition - Stack Overflow
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 "") .............
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.apply.html
pandas.DataFrame.apply โ€” pandas 3.0.1 documentation
If โ€œcompatโ€, will if possible first translate the func into pandas methods (e.g. Series().apply(np.sum) will be translated to Series().sum()). If that doesnโ€™t work, will try call to apply again with by_row=True and if that fails, will call apply again with by_row=False (backward compatible).
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python pandas โ€บ apply lambda functions to pandas dataframe
How to Apply Lambda Function to Pandas DataFrame | Delft Stack
February 2, 2024 - We can also apply the conditional statements on pandas dataframes using the lambda function. We used the conditional statement inside the lambda function in the following example. We applied the condition on the Monthly Income column. If the monthly income is greater and equal to 5000, add Stable inside the Category column; otherwise, add UnStable.
Top answer
1 of 4
224

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
๐ŸŒ
CSDN
devpress.csdn.net โ€บ python โ€บ 63046073c67703293080c104.html
Using Apply in Pandas Lambda functions with multiple if statements_python_Mangs-Python
df['Classification']=df['Size'].apply(lambda x: "<1m" if x<1000000 else "1-10m" if 1000000<x<10000000 else ...)
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas apply() with lambda examples
Pandas apply() with Lambda Examples - Spark By {Examples}
June 17, 2025 - A lambda function is a small anonymous function that can take any number of arguments and execute an expression. ... In this article, I will explain how to use a Pandas DataFrame.apply() with lambda by examples. lambda expressions are utilized to construct anonymous functions.
๐ŸŒ
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.
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ learn how to use lambda functions in python easily and effectively
Learn How to Use Lambda Functions in Python Easily and Effectively
December 1, 2024 - We can do this with the apply() ... a dataframe. If the axis argument in the apply() function is 0, then the lambda function gets applied to each column, and if 1, then the function gets applied to each row....