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 - Lambda supports only a single if-else, not chained conditions. You can't use elif inside a lambda like in regular Python. To use multiple conditional checks, define a function and pass it to apply(). ... import pandas as pd df = pd.DataFram...
Discussions

python - Using lambda if condition on different columns in Pandas dataframe - Stack Overflow
df["col3"] = df[["col1", ... else "return this because none of the above statements were true", axis=1 ) ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 0 Using lambda IF condition on columns in Pandas to extract ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Lambda including if...elif...else - Stack Overflow
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
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
if statement - Python: using lambda function on Pandas Series, if.. else - Stack Overflow
I am trying to apply a filter on a series of values stored in a pandas series object. The desired output is the value itself if it meets the criterion otherwise zero. I can only get it to half work: More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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 - For example, the following Lambda if-else Pandas function checks if a value is less than 1000000 and returns "Small" if it is or "Large" if it is not- ... You can use the following code to apply a lambda function to a column in a DataFrame to categorize ages-
๐ŸŒ
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 - The generic structure of the code using lambda function is: 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 ...
๐ŸŒ
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)
Find elsewhere
๐ŸŒ
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.
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
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ ways-to-apply-an-if-condition-in-pandas-dataframe
How to apply if condition in Pandas DataFrame - GeeksforGeeks
November 21, 2024 - 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)
๐ŸŒ
Statology
statology.org โ€บ home โ€บ pandas: how to use apply & lambda together
Pandas: How to Use Apply & Lambda Together
June 23, 2022 - #create new column called 'status' df['status'] = df['points'].apply(lambda x: 'Bad' if x < 20 else 'Good') #view updated DataFrame print(df) team points assists status 0 A 18 5 Bad 1 B 22 7 Good 2 C 19 7 Bad 3 D 14 9 Bad 4 E 14 12 Bad 5 F 11 9 Bad 6 G 20 9 Good 7 H 28 4 Good
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71260517 โ€บ python-lambda-function-if-else-condition โ€บ 71260558
pandas - Python lambda function if else condition - Stack Overflow
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 "") .............
๐ŸŒ
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.
๐ŸŒ
Medium
medium.com โ€บ @amit25173 โ€บ understanding-lambda-functions-in-pandas-e4588c53cc89
Understanding Lambda Functions in Pandas | by Amit Yadav | Medium
March 6, 2025 - You can use it across multiple columns by setting axis=1. This tells Pandas, โ€œHey, apply the function row-wise.โ€ ... # Creating a DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # Summing values from columns A and B df['sum'] ...
๐ŸŒ
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
df.apply((lambda x: x / x.sum() if x/x.sum() >= 0 else None), axis=1).fillna(0) to get, if cell is same at total then calculate x/total: A B C D 2/15 5/15 0 12/15 ยท I get: 'The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How can i improve the code. python ยท pandas ยท
๐ŸŒ
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 - As you can see, the above code will raise an error because it doesnโ€™t correctly format the if-elif-else logic within the lambda function. So, what are the valid alternatives? One straightforward approach is to nest the if statements: df["one"].apply(lambda x: x * 10 if x < 2 else (x ** 2 if x < 4 else x + 10))