For multiple conditions ie. (df['employrate'] <=55) & (df['employrate'] > 50)

use this:

df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

or you can do it this way as well,

gm.loc[(gm['employrate'] <55) & (gm['employrate'] > 50),'employrate']=11

here informal syntax can be:

<dataset>.loc[<filter1> & (<filter2>),'<variable>']='<value>'

out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

therefore syntax we used here is:

 df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])

for single condition, ie. ( 'employrate'] > 70 )

       country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

use this:

df.loc[df['employrate'] > 70, 'employrate'] = 7

       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

therefore syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

Answer from Harshit Jain on Stack Overflow
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas replace values based on condition
Pandas Replace Values based on Condition - Spark By {Examples}
June 18, 2025 - You can replace all values or selected values in a column of pandas DataFrame based on condition by using DataFrame.loc[], np.where() and DataFrame.mask()
๐ŸŒ
Statology
statology.org โ€บ home โ€บ pandas: how to replace values in column based on condition
Pandas: How to Replace Values in Column Based on Condition
October 26, 2021 - Notice that each of the three values in the โ€˜pointsโ€™ column that were greater than 10 got replaced with the value 20. ... import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'position': ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'], 'points': [5, 7, 7, 9, 12, 13, 9, 14], 'assists': [3, 8, 2, 6, 6, 5, 9, 5]}) #view DataFrame df team position points assists 0 A G 5 3 1 A G 7 8 2 A F 7 2 3 A F 9 6 4 B G 12 6 5 B G 13 5 6 B F 9 9 7 B F 14 5
Discussions

python - Replacing values in a pandas dataframe based on multiple conditions - Stack Overflow
0 Python:Fill a column in a dataframe if a condition is met ยท 0 Changing values in each row of a column based on values in other columns of the corresponding row (Python/Pandas) More on stackoverflow.com
๐ŸŒ stackoverflow.com
data mining - Pandas change value of a column based another column condition - Data Science Stack Exchange
I have values in column1, I have columns in column2. What I want to achieve: Condition: where column2 == 2 leave to be 2 if column1 90. Here is what i did s... More on datascience.stackexchange.com
๐ŸŒ datascience.stackexchange.com
Python Pandas replace value based on multiple column conditions - Stack Overflow
I'm not sure if there is an issue setting a columns value that is also in the where condition off hand but you could always create a temp column and rename/drop other outputs based on that. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Pandas DataFrame: replace all values in a column, based on condition - Stack Overflow
I have a simple DataFrame like the following: Team First Season Total Games 0 Dallas Cowboys 1960 894 1 Chicago Bears 1920 1357 2 Green Bay Packers 1921 1339 3 Miami Dolphins 1966 792 4 Baltimore R... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 27, 2018
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ pandas โ€บ conditional changes in pandas dataframe
Conditional Changes in Pandas Dataframe - Scaler Topics
May 4, 2023 - There are several methods for ... dataframe with new values based on the condition. We can also replace the values in columns by using the if condition in Pandas DataFrame. We can also apply multiple conditions at the same time and change our data....
Top answer
1 of 4
13

For multiple conditions ie. (df['employrate'] <=55) & (df['employrate'] > 50)

use this:

df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

or you can do it this way as well,

gm.loc[(gm['employrate'] <55) & (gm['employrate'] > 50),'employrate']=11

here informal syntax can be:

<dataset>.loc[<filter1> & (<filter2>),'<variable>']='<value>'

out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

therefore syntax we used here is:

 df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])

for single condition, ie. ( 'employrate'] > 70 )

       country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

use this:

df.loc[df['employrate'] > 70, 'employrate'] = 7

       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

therefore syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

2 of 4
9
df1.apply(np.sign).replace({-1: 'down', 1: 'up', 0: 'zero'})

Output:

      0     1     2
0  down    up    up
1    up  down  down
2    up  down  down
3  down  down    up
4  down  down    up
5  down    up    up
6  down    up  down
7    up  down  down
8    up    up  down
9  down    up    up

P.S. Getting exactly zero with randn is pretty unlikely, of course

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ data analysis โ€บ how-to-replace-values-in-column-based-on-condition-in-pandas
How to Replace Values in Column Based on Condition in Pandas? - GeeksforGeeks
November 15, 2024 - The apply() function in combination with a lambda function is a flexible method for applying conditional replacements based on more complex logic. Here, we will replace 'female' with 0 in the gender column using the apply() function and lambda.
๐ŸŒ
Python Guides
pythonguides.com โ€บ pandas-replace-multiple-values-in-column-based-on-condition-in-python
Replace Multiple Values In Pandas DataFrame Based On Conditions
June 9, 2025 - Python replace() method allows you to replace multiple values at once using a dictionary mapping. import pandas as pd # DataFrame with US state abbreviations data = { 'State': ['CA', 'NY', 'TX', 'FL', 'IL', 'AZ'], 'Revenue': [10000, 8500, 9200, 7500, 8000, 6500] } df = pd.DataFrame(data) ...
๐ŸŒ
Python Examples
pythonexamples.org โ€บ pandas-dataframe-replace-values-in-column-based-on-condition
Pandas DataFrame - Replace values in column based on condition
In the following program, we will replace those values in the column 'a' that satisfy the condition that the value is less than zero. import pandas as pd df = pd.DataFrame([ [-10, -9, 8], [6, 2, -4], [-8, 5, 1]], columns=['a', 'b', 'c']) df.loc[(df.a < 0), 'a'] = 0 print(df) ... You can also replace the values in multiple values based on a single condition.
Find elsewhere
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ pandas
pandas: Replace values based on conditions with where(), mask() | note.nkmk.me
January 17, 2024 - This article explains how to replace values based on conditions in pandas. You can perform conditional operations like if then ... or if then ... else ... on DataFrame or Series. Use the where() metho ...
๐ŸŒ
RS Blog
reneshbedre.com โ€บ blog โ€บ replace-column-values-based-on-condition-pandas.html
How to replace column values in pandas DataFrame based on column conditions
December 18, 2022 - This method is more suitable if you want to update the large number of values based on condition in a column. ... condition: conditional expression true_value: Old value will be replaced with this true value if the condition is True false_value: Old value will be replaced with this value if the condition is False ยท import pandas as pd # create a random dataframe df = pd.DataFrame({'name':['Adams', 'Jones', 'Frank', 'Smith', 'Davis'], 'age':[25, 30, 28, 35, 22], 'weight':[74, 90, 85, 65, 92]}) # output name age weight 0 Adams 25 74 1 Jones 30 90 2 Frank 28 85 3 Smith 35 65 4 Davis 22 92 # replace the weight value with 92 if it is 90 df['weight'].mask(df['weight'] == 90, 98, inplace=True) # output name age weight 0 Adams 25 74 1 Jones 30 98 2 Frank 28 85 3 Smith 35 65 4 Davis 22 92
๐ŸŒ
Arab Psychology
scales.arabpsychology.com โ€บ psychological scales โ€บ how to use pandas to replace values in column based on condition
How To Use Pandas To Replace Values In Column Based On Condition
November 15, 2023 - Pandas provides a method called .loc to replace values in a column based on condition. It takes a list of conditions as the first argument and a list of values to replace the conditions with as the second argument. The syntax is df.loc[conditions, โ€˜columnโ€™] = new_values.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-replace-values-in-columns-based-on-condition-in-pandas
How to Replace Values in Columns Based on Condition in Pandas
March 27, 2026 - import pandas as pd import numpy as np data = { 'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'], 'age': [25, 35, 45, 55, 65], 'gender': ['F', 'M', 'M', 'F', 'F'] } df = pd.DataFrame(data) # Replace age with 0 where gender is 'M', keep original age otherwise df['age'] = np.where(df['gender'] == 'M', 0, df['age']) print(df) name age gender 0 Alice 25 F 1 Bob 0 M 2 Charlie 0 M 3 David 55 F 4 Emily 65 F ยท Pandas offers multiple methods for conditional value replacement.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.replace.html
pandas.DataFrame.replace โ€” pandas 3.0.5 documentation
Replace values based on boolean condition. ... Apply a function to a Dataframe elementwise. ... Map values of Series according to an input mapping or function. ... Simple string replacement. ... Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same. Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched.
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ how-to-replace-all-values-in-a-column-based-on-condition.aspx
Pandas: How to replace all values in a column, based on condition?
September 21, 2023 - # Importing pandas package import pandas as pd # creating a dictionary of student marks d = { "Players":['Sachin','Ganguly','Dravid','Yuvraj','Dhoni','Kohli'], "Format":['ODI','ODI','ODI','ODI','ODI','ODI'], "Runs":[15921,7212,13228,1900,4876,8043] } # Now we will create DataFrame df = pd.DataFrame(d) # Viewing the DataFrame print("DataFrame:\n",df,"\n\n") # Replacing thr values of column Format df.loc[(df.Format == 'ODI' ), 'Format'] = 'TEST' # Display modified DataFrame print("Modified DataFrame:\n",df)
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ version โ€บ 2.1 โ€บ reference โ€บ api โ€บ pandas.DataFrame.replace.html
pandas.DataFrame.replace โ€” pandas 2.1.4 documentation
Replace values based on boolean condition. ... Apply a function to a Dataframe elementwise. ... Map values of Series according to an input mapping or function. ... Simple string replacement. ... Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same. Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched.
Top answer
1 of 4
13

What I want to achieve: Condition: where column2 == 2 leave to be 2 if column1 < 30 elsif change to 3 if column1 > 90

This can be simplified into where (column2 == 2 and column1 > 90) set column2 to 3. The column1 < 30 part is redundant, since the value of column2 is only going to change from 2 to 3 if column1 > 90.

In the code that you provide, you are using pandas function replace, which operates on the entire Series, as stated in the reference:

Values of the Series are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value.

This means that for each iteration of for x in filter1 your code performs global replacement, which is not what you want to do - you want to update the specific row of column2 that corresponds to x from column1 (which you are iterating over).

the problem is 2 does not change to 3 where column1 > 90

This is truly strange. I would expect the code you provided to have changed every instance of 2 in column2 to 3 as soon as it encountered an x >= 30, as dictated by your code conditional statement (the execution of the else branch). This discrepancy may stem from the fact that you are assigning to column2 the result of global replacement performed on the column Output (the contents of which are unknown). In any case, if you want your program to do something under a specific condition, such as x > 90, it should be explicitly stated in the code. You should also note that the statement data['column2'] = data['column2'].replace([2], [2]) achieves nothing, since 2 is being replaced with 2 and the same column is both the source and the destination.

What you could use to solve this particular task is a boolean mask (or the query method). Both are explained in an excellent manner in this question.

Using a boolean mask would be the easiest approach in your case:

mask = (data['column2'] == 2) & (data['column1'] > 90)
data['column2'][mask] = 3

The first line builds a Series of booleans (True/False) that indicate whether the supplied condition is satisfied. The second line assigns the value 3 to those rows of column2 where the mask is True.

2 of 4
12

I've had success approaching this in a slightly different way.

import numpy as np

data['column2'] = np.where((data['column1'] < 30)
                           & (data['column2'] ==2), #Identifies the case to apply to
                           data['column2'],      #This is the value that is inserted
                           data['column2'])      #This is the column that is affected
data['column2'] = np.where((data['column1'] > 90)
                           & (data['column2'] ==2), #For rows with column1 > 90
                           data['column3'],      #We place column3 values
                           data['column2'])      #In column two

This is a little wordier than a loop, but I've found it to be the most intuitive way to do this sort of data manipulation with pandas.

Top answer
1 of 2
2

You are very close, but you have the arguments switched in np.where, the syntax is np.where(cond, if_cond_True, if_cond_False). The columns A and B should have the value of column if the condition is satisfied (if_cond_True), otherwise they keep their original values (if_cond_False).

import pandas as pd
import numpy as np 

data_in = {'A':['A1', '', '', 'A4',''],
        'B':['', 'B2', 'B3', '',''],
        'C':['C1','C2','','','C5']}

df_in = pd.DataFrame(data_in)

maskA = df_in['A'] != ''   # A not empty
maskB = df_in['B'] != ''   # B not empty
maskC = df_in['C'] != ''   # C not empty

# If the column havs NaNs instead of '' then use : 
#
# maskA = df_in['A'].notnull()   # A not empty
# maskB = df_in['B'].notnull()   # B not empty
# maskC = df_in['C'].notnull()   # C not empty

# If A and C are not empty, A = C, else A keep its value 
df_in['A'] = np.where(maskA & maskC, df_in['C'], df_in['A'])

# If B and C are not empty, B = C, else B keep its value
df_in['B'] = np.where(maskB & maskC, df_in['C'], df_in['B'])

# If (A and C are not empty) or (B and C are not empty),
# C should be empty, else C keep its value
df_in['C'] = np.where((maskA & maskC) | (maskB & maskC), "", df_in['C'])

Output

>>> df_in 

    A   B   C
0  C1        
1      C2    
2      B3    
3  A4        
4          C5
2 of 2
1

I'm not sure if there is an issue setting a columns value that is also in the where condition off hand but you could always create a temp column and rename/drop other outputs based on that.

An alternative is to use the apply function.

def update_data(row):
    a = row['A']
    b = row['B']
    c = row['C']

    if not c.isna():
        if a.isna():
            row['A'] = c

        if b.isna():
            row['B'] = c

    return row

df_new = df.apply(update_data, axis=1)

Apply will definitely get you the correct result, however, I'm not certain as to what your desired outcome is so you may need to adjust the logic. The above will set columns A and/or B = C if A is a na type object ("" is a na type) and C is not a na type object. Otherwise it will not update anything.

I'm not sure what you want by "clear column C". You can just drop the column if that's what you want. If you want to change the value you can do so in the update_data function or do a string replace.

๐ŸŒ
Medium
medium.com โ€บ @RedHairedGirl โ€บ pandas-dataframe-a-comprehensive-guide-to-replace-values-based-on-condition-27d89d830bb4
Pandas DataFrame: A Comprehensive Guide to Replace Values Based on Condition - RedHairedGirl (aka PLIM) - Medium
November 21, 2024 - For a pandas DataFrame, there are various ways to replace the values in a column. In this Jupyer Notebook, I have illustrated most (if not all) of the ways one could use to replace the values based on 1โ€“2 conditions, or to replace values with that in another column.
๐ŸŒ
Python Guides
pythonguides.com โ€บ pandas-replace-multiple-values
Replace Multiple Values In Pandas DataFrame Using Str.Replace()
May 22, 2025 - The loc[] method in Python allows you to replace values based on conditions, which gives you more flexibility. Hereโ€™s an example with sales data categorization: import pandas as pd # Sample US sales data data = { 'Product': ['Laptop', 'Smartphone', 'Tablet', 'Monitor', 'Keyboard'], 'Sales': ...
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-replace-all-values-in-a-pandas-dataframe-column-based-on-a-condition
How to Replace All Values in a Pandas DataFrame Column Based on a Condition | Saturn Cloud Blog
May 1, 2026 - Handling: Ensure that the replacement value has a compatible data type with the column being modified. ... Error: Trying to implement complex conditions may lead to syntax errors or unexpected behavior. Handling: Break down complex conditions into simpler steps or use additional boolean arrays to construct the final condition. In this article, we have demonstrated how to replace all values in a Pandas DataFrame column based on a condition.