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.

Answer from Vlad_Z on Stack Exchange
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.replace.html
pandas.DataFrame.replace โ€” pandas 3.0.5 documentation
For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column โ€˜aโ€™ and the value โ€˜zโ€™ in column โ€˜bโ€™ and replaces these values with whatever is specified in value.
๐ŸŒ
DataScientYst
datascientyst.com โ€บ replace-values-column-based-another-dataframe-pandas
How to Replace Values in Column Based On Another DataFrame in Pandas
January 23, 2026 - In this quick tutorial, we'll cover how we can replace values in a column based on values from another DataFrame in Pandas. We can use the following syntax to margin on a single axis column or row in Pandas: (1) matching indices df2.loc[:, ['ID']] = df1[['ID']] (2) non
Discussions

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 - Change values in one column on the basis of the values in another column - Stack Overflow
I'm trying to reproduce my Stata code in Python, and I was pointed in the direction of Pandas. I am, however, having a hard time wrapping my head around how to process the data. Let's say I want to More on stackoverflow.com
๐ŸŒ stackoverflow.com
how to update a pandas dataframe column value, when a specific string appears in another column?
It's not something you'd really use .apply for. You would use boolean indexing, e.g. df['A'].str.contains('foo') would give you a Series of True/False values. You can then use .loc to set column(s) to a particular value for the True rows: df.loc[df['A'].str.contains('foo'), 'B'] = 'bar' More on reddit.com
๐ŸŒ r/learnpython
7
3
June 24, 2024
python - Replace column value based on value in other column, for all rows in a pandas dataframe - Stack Overflow
I am having trouble thinking pythonically about something, and would love some guidance. I have a dataframe that contains columns with dates of events at which certain files should be uploaded, an... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ best way to replace values in one column from another column in pandas?
r/learnpython on Reddit: Best way to replace values in one column from another column in pandas?
October 20, 2022 -

Original range:

old_items new_items
item1 item6
item2 0
item3 item7
item4 0
item5 item8

Desired output:

old_items new_items
item6 item6
item2 0
item7 item7
item4 0
item8 item8

My stupid solution:

old_items = list(df['old_items'])
new_items = list(df['new_items'])
proper_items = []

for x in range(len(old_items)):
    if new_items[x] != 0:
        proper_items.append(new_items[x])
    else:
        proper_items.append(old_items[x])

df['old_items'] = proper_items
๐ŸŒ
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()
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.

๐ŸŒ
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.
Top answer
1 of 8
328

One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.

Assuming you can load your data directly into pandas with pandas.read_csv then the following code might be helpful for you.

import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"

As mentioned in the comments, you can also do the assignment to both columns in one shot:

df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'

Note that you'll need pandas version 0.11 or newer to make use of loc for overwrite assignment operations. Indeed, for older versions like 0.8 (despite what critics of chained assignment may say), chained assignment is the correct way to do it, hence why it's useful to know about even if it should be avoided in more modern versions of pandas.


Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:

import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"
2 of 8
53

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

df = pd.DataFrame({"ID":[103,104], "First_Name":["a","c"], "Last_Name":["b","d"]})
        ID First_Name Last_Name
    0  103          a         b
    1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])
Find elsewhere
๐ŸŒ
Python Examples
pythonexamples.org โ€บ pandas-dataframe-replace-values-in-column-based-on-condition
Pandas DataFrame - Replace values in column based on condition
new_value replaces (since inplace=True) existing value in the specified column based on the condition. In the following program, we will use DataFrame.where() method and replace those values in the column 'a' that satisfy the condition that the value is less than zero. import pandas as pd df ...
๐ŸŒ
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.
๐ŸŒ
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 - #replace any values in 'points' column greater than 10 with 20 df.loc[df['points'] > 10, 'points'] = 20 #view updated 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 20 6 5 B G 20 5 6 B F 9 9 7 B F 20 5
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to update a pandas dataframe column value, when a specific string appears in another column?
r/learnpython on Reddit: how to update a pandas dataframe column value, when a specific string appears in another column?
June 24, 2024 -

So, i've figured out how to use the pandas apply method to update/change the values of a column, row-wise based on multiple comparisons like this:

# for each row, if the value of both 'columns to check' are 'SOME STRING', change to 'NEW STRING
# otherwise leave it as is
my_df ['column_to_change'] = df.apply(lambda row: 'NEW STRING' if row['column_to_check_1'] and row['column_to_check_2'] == 'SOME STRING' else row['column_to_change'], axis=1)

Now, I can't figure out how to expand that beyond simple comparison operators. The specific example I'm trying to solve is:

" for each row, if the string value in COLUMN A contains 'foo', change the value in COLUMN B to 'bar', otherwise leave it as is"

I think this is all right, except the ##parts between the hashmarks##

my_df ['columb_b'] = df.apply(lambda row: 'bar' if ##column A contains 'foo'## else row['columb_b'], axis=1)
๐ŸŒ
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.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ version โ€บ 2.1 โ€บ reference โ€บ api โ€บ pandas.DataFrame.replace.html
pandas.DataFrame.replace โ€” pandas 2.1.4 documentation
Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ replace-values-of-a-dataframe-with-the-value-of-another-dataframe-in-pandas
Replace values of a DataFrame with the value of another DataFrame in Pandas - GeeksforGeeks
January 17, 2022 - Letรขย€ย™s see how to Select rows based on some conditions in Pandas DataFrame. Selecting rows based on particular column value using '>', '=', '=', '<=', '!=' operator. Code #1 : Selecting all the rows from the given dataframe in which 'Percentage' is greater than 80 using basic method.
Top answer
1 of 1
6

So, I can answer your base question pretty easily, but there's a couple of style things I think you might want to change that I'd like to get into. I'm fairly certain this question has been addressed in other threads, but you've got a couple of problems wrapped up in 1 so I'm just going to address them here

For every row in the dataframe If the value in the VisitName column == X Change the value in ColumnA to "Not Expected"

You want to be using index slices to set values. Get a boolean mask of the dataframe based on the logic you want, use that to create a new dataframe containing only the rows that you want to update, get the index of this new dataframe, and use this index with the original dataframe to change the values over.

    import pandas as pd
    df = pd.DataFrame(data=None, index=["X", "Y", "Z"], columns=["VisitName",
    "ColumnA", "ColumnB"])

    not_expected_index = df[df.loc[:, "VisitName"] == "X"].index
    df.loc[not_expected_index, "ColumnA"] = "Not Expected"

This is the preferred way in pandas to change values in a DataFrame based on other values in another column.

Now, there's a couple of things about the original DataFrame you posted that I'd like to mention. First, if you already have Null values in the dataframe cells, then you can use the pandas dataframe fillna method to populate these values.

    df.fillna("Not Expected")

Second, why do you want to use the string "NN" or "Not Needed" over the default Null value? For any operations within pandas, I prefer to stick with the actual null values, so that you can use aggregation functions like sum or count freely on dataframes with null values.

Second, the index contains repeated values:

    df.index = ["X", "X", "Y", "Z", "X", "Z"]

Dataframes will allow duplicate index values, but they can behave in funny ways that you need to be aware of.

For example:

    print(df)

returns

        VisitName ColumnA ColumnB
    X       NaN     NaN     NaN
    X       NaN     NaN     NaN
    Y       NaN     NaN     NaN
    Z       NaN     NaN     NaN
    X       NaN     NaN     NaN
    Z       NaN     NaN     NaN

setting a value in VisitName for X

    df.loc["X", "VisitName"] = "test"

returns

      VisitName ColumnA ColumnB
    X      "test"   NaN     NaN
    X      "test"   NaN     NaN
    Y       NaN     NaN     NaN
    Z       NaN     NaN     NaN
    X      "test"   NaN     NaN
    Z       NaN     NaN     NaN

If I were tackling this problem, I'd either use the date as the index, with a True or False value in a file's column depending on whether it needs to be sent or not on that date,

     index       File1 File2 File3 
    8/01/17      True  False True
    8/08/17      False True  True
    8/15/17      True  True  False 
    8/24/17      False True  False 
    9/01/17      False False False 
    9/12/17      True  False True

or I'd just use an integer index, with a column for the date and a column for what file is being sent.

  index    date     file
    0      8/01/17   1
    1      8/01/17   2
    2      8/08/17   2
    3      8/15/17   1
    4      8/15/17   2
    5      8/15/17   3

I mean, if you're locked into using the other setup, that's fine, but I think these would be easier dataframe setups to work with, since they'd support groupby methods more easily.

Also, keep in mind that if you're using a for loop, then you might as well not be using pandas. The whole point of pandas is that it uses C to speed up index operations. Never use

    for row in df.index:
        df.loc[row, 'columna'] += 2.

Always use

    df.loc[:, 'columna'] += 2.
๐ŸŒ
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 - This article demonstrates five different methods to conditionally replace column values. The loc function allows you to access and modify specific rows and columns in a DataFrame based on boolean conditions ? ... import pandas as pd data = { 'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'], 'age': [25, 35, 45, 55, 65], 'gender': ['F', 'M', 'M', 'F', 'F'] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) # Replace gender with 'M' where age >= 50 df.loc[df['age'] >= 50, 'gender'] = 'M' print("\nAfter replacement:") print(df)
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ pandas dataframe replace() โ€“ by examples
Pandas DataFrame replace() - by Examples - Spark By {Examples}
October 10, 2024 - pandas.DataFrame.replace() function is used to replace values in columns (one value with another value on all columns). It is a powerful tool for data