is that what you want?

In [300]: frame[['b','c']].apply(lambda x: x['c'] if x['c']>0 else x['b'], axis=1)
Out[300]:
0   -1.099891
1    0.582815
2    0.901591
3    0.900856
dtype: float64
Answer from MaxU - stand with Ukraine 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.
Discussions

Implementing if-else in python dataframe using lambda when there are multiple variables - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
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
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
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 ... More on stackoverflow.com
🌐 stackoverflow.com
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)
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
🌐
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. In general, JIT compilation is only possible when the function passed to apply has type stability (variables in the function do not change their type during the execution).
Find elsewhere
🌐
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)
🌐
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.
🌐
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....
🌐
Javatpoint
javatpoint.com › applying-lambda-functions-to-pandas-dataframe
Applying Lambda functions to Pandas Dataframe - Javatpoint
Applying Lambda functions to Pandas Dataframe with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
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)
🌐
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')
🌐
Medium
medium.com › analytics-vidhya › how-to-use-pandas-lambda-and-assign-8a384e2d8769
How to use Pandas: lambda and assign | by Louis de Bruijn | Analytics Vidhya | Medium
July 20, 2021 - Applying ‘the Zen of Python’ to Pandas: Why explicit is better than implicit. Make use of the latest Pandas functionalities and a lambda function
🌐
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')
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-use-if-else-elif-in-python-lambda-functions
How to use if, else & elif in Python Lambda Functions - GeeksforGeeks
July 23, 2025 - We will implement this using the lambda function. ... Here, statement1 will be returned when if the condition is true, statement2 will be returned when elif true, and statement3 will be returned when else is executed.
🌐
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 - The lambda function is a short, anonymous function that takes in a value and returns a value based on a certain condition. Let’s take an example to understand how the if-else function works in Pandas DataFrame.