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
๐ŸŒ
Data to Fish
datatofish.com โ€บ if-condition-in-pandas-dataframe
Two Ways to Apply an If-Condition on a pandas DataFrame
df.loc[df['column'] == condition_value, 'target_column' ] = then_value df['target_column'] = df['column'].apply(lambda x: then_value if x == condition_value)
Discussions

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
pandas - How to use Python lambda without else? - Stack Overflow
I need to change the value of myCol if a condition is true. If the condition is not true, nothing should happen (if I do else None, it writes None as value to myCol) tmp_df = someDataframe.groupby... 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
python - lambda if statement or do nothing pandas - Stack Overflow
Hey I looked through some of the post but I could not find a direct answer. I am working on a pandas DataFrame which has two columns ZipCode and ZipCodePlusFour. Some of the ZipCodePlusFour cells are More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 4, 2017
๐ŸŒ
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.
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
๐ŸŒ
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?
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ ways-to-apply-an-if-condition-in-pandas-dataframe
How to apply if condition in Pandas DataFrame - GeeksforGeeks
November 21, 2024 - In Pandas DataFrames, applying conditional logic to filter or modify data is a common task. Let's explore different ways to apply an 'if condition' in Pandas DataFrame. We can apply an "if condition" by using apply() with a lambda function.
๐ŸŒ
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 - Another way to use if-else without using lambda function is as follow: # Applying if-else statement to categorize students df['Result'] = ['Pass' if score >= 50 else 'Fail' for score in df['Score']] The provided code produces identical results, but it is more accessible for individuals who may not be familiar with Pythonโ€™s lambda function. The if-else function is a powerful tool that allows you to apply a certain condition to a Pandas ...
๐ŸŒ
ListenData
listendata.com โ€บ home โ€บ python
Python Lambda Function with Examples
sample['newvar1'] = sample.apply(lambda x: np.nan if x['var1'] < 90 else x['var1'], axis=1) How to read the above lambda function ยท x: value_if_condition_true if logical_condition else value_if_condition_false axis=1 tells python to apply function to each row of a particular column. By default, it is 0 which means apply function to each column of a row. There is one more way to write the above function without specifying axis option.
๐ŸŒ
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 "") .............
๐ŸŒ
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 - In this article we will discuss how to use if , else if and else in a lambda functions in Python. Will also explain how to use conditional lambda function
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.apply.html
pandas.DataFrame.apply โ€” pandas 3.0.1 documentation
>>> df.apply(lambda x: [1, 2], axis=1, result_type="broadcast") A B 0 1 2 1 1 2 2 1 2 ยท Advanced users can speed up their code by using a Just-in-time (JIT) compiler with apply. The main JIT compilers available for pandas are Numba and Bodo.
๐ŸŒ
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'] ...
๐ŸŒ
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')
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas apply() with lambda examples
Pandas apply() with Lambda Examples - Spark By {Examples}
June 17, 2025 - Following are quick examples of how to use the lambda function with Pandas DataFrame.apply(). # Quick examples of apply with lambdaes # Example 1: Apply a lambda function to each column df2 = df.apply(lambda x : x + 10) # Example 2: Using Dataframe.apply() and lambda function df["A"] = df["A"].apply(lambda x: x-2) # Example 3: Apply function NumPy.square() # To square the values of two rows #'A'and'B df2 = df.apply(lambda x: np.square(x) if x.name in ['A','B'] else x) # Example 4: Using DataFrame.map() to Single Column df['A'] = df['A'].map(lambda A: A/2.) # Example 5: Using DataFrame.assign() and Lambda df2 = df.assign(B=lambda df: df.B/2) The purpose of using apply() with lambda in pandas is to perform custom operations on a Series or DataFrame by applying a short, inline function to each element, row, or column.