You need to select that column:

In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df

Out[41]:
                 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 Ravens             1          326
5  San Franciso 49ers          1950         1003

So the syntax here is:

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

You can check the docs and also the 10 minutes to pandas which shows the semantics

EDIT

If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int this will convert True and False to 1 and 0 respectively:

In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df

Out[43]:
                 Team  First Season  Total Games
0      Dallas Cowboys             0          894
1       Chicago Bears             0         1357
2   Green Bay Packers             0         1339
3      Miami Dolphins             0          792
4    Baltimore Ravens             1          326
5  San Franciso 49ers             0         1003
Answer from EdChum on Stack Overflow
๐ŸŒ
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.
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
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
A most efficient way of using conditional replacement in pandas
You can assign multiple columns to the same value at the same time. >>> df foo bar baz 0 1 4 7 1 2 5 8 2 1 6 9 >>> df.loc[ df['foo'] == 1, ['baz', 'bar']] = '-' >>> df foo bar baz 0 1 - - 1 2 5 8 2 1 - - It's .loc[rows, columns] = value >>> rows = df['foo'] == 1 >>> columns = 'bar', 'baz' >>> df.loc[rows, columns] = '-' >>> df foo bar baz 0 1 - - 1 2 5 8 2 1 - - More on reddit.com
๐ŸŒ r/learnpython
2
1
November 9, 2022
Pandas: Need to replace only a certain value with another value from a different dataframe.
df = pd.merge(df1, df2, left_on='Project Name', right_on='Name of Project', how='left') cond = df['Project Owner'] == 'Default' df.loc[cond, 'Project Owner'] = df.loc[cond, 'Owner of Project'] There's probably an easier solution, but I can't think of it. Edit: Actually there is something a little easier. Instead of using the condition and loc, you can use combine_first to combine the non NA values between the two columns df = pd.merge(df1, df2, left_on='Project Name', right_on='Name of Project', how='left') df['Project Owner'] = df['Project Owner'].combine_first(df['Owner of Project']) Use this if you want to drop the two new columns. df = df.drop(columns=['Name of Project', 'Owner of Project']) More on reddit.com
๐ŸŒ r/learnpython
5
1
January 31, 2024
๐ŸŒ
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 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.

๐ŸŒ
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.
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ conditional-replacement-in-pandas-a-quick-guide-for-data-scientists
Conditional Replacement in Pandas A Quick Guide for Data Scientists | Saturn Cloud Blog
May 1, 2026 - This can be done using pandas' replace method, which allows you to specify the value to replace and the replacement value based on a condition. To perform conditional replacement in pandas, you can use the replace method on a DataFrame or a ...
Find elsewhere
๐ŸŒ
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)
๐ŸŒ
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()
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ pandas โ€บ conditional changes in pandas dataframe
Conditional Changes in Pandas Dataframe - Scaler Topics
May 4, 2023 - 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.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python โ€บ pandas
Replace values based on conditions with where(), mask()
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 ...
๐ŸŒ
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
๐ŸŒ
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
July 10, 2023 - 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 ?
๐ŸŒ
Favtutor
favtutor.com โ€บ articles โ€บ pandas-replace-column-values
Pandas DataFrame: Replace Column Values (with code)
December 15, 2023 - Learn how to replace column values in a Pandas DataFrame using replace, apply and loc methods with Python examples.
๐ŸŒ
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 - As a data scientist or software engineer you may come across a situation where you need to replace all values in a Pandas DataFrame column based on a certain condition This can be easily achieved using the powerful DataFrame capabilities of Pandas library in Python
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ a most efficient way of using conditional replacement in pandas
r/learnpython on Reddit: A most efficient way of using conditional replacement in pandas
November 9, 2022 -

An example of code I have to replace based on "No" string:

rolledup_data.loc[rolledup_data['FA to be replaced by sourcing activity']=="No",'PMO status'] = "-" #setting no to nan
rolledup_data.loc[rolledup_data['FA to be replaced by sourcing activity']=="No",'Early/On Time/Late?'] = "-"

Logic i want to incorporate for replacement with blanks: If first column contains the string No, then set PMO status // Early/On Time/Late? columns to "-" (blank).

Is there a quicker way to do this then writing same thing line by line where conditional column FA to be replaced by sourcing activity to be replaced is same but replacement columns are different?

FA to be replaced by sourcing activityPMO statusEarly/On Time/Late?
No (condition)In progress (should be blank)Ear On (should be blank)
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas: need to replace only a certain value with another value from a different dataframe.
r/learnpython on Reddit: Pandas: Need to replace only a certain value with another value from a different dataframe.
January 31, 2024 -

I'm losing my mind on this one. I have two dataframes. For simplicity's sake, in df1, let's say there's a column with a project name, and a column with the project owner. Due to a change in systems, some project owners have been replaced with "Default." In df2, I have all the projects and project owners, but only for the "Default" folk. There are, of course, many other columns on both dataframes, but I'm omitting them. Also, the dataframes have completely different column names. I only mention because it's one of the errors I've run into. This is for a script I run every week for work that needs to be changed due to the aforementioned new system.

Example of df1:

Project Name Project Owner
Project A Bob Jones
Project B Default
Project C Default
Project D John Roberts

Example of df2:

Name of Project Owner of Project
Project B Bertha Thomas
Project C Jane Smith

I've tried:

project_dict = dict(zip(df2['Name of Project'], df2['Owner of Project']))
df['Project Owner'] = df['Project Name'].replace(project_dict)

Which outputs:

Project Name Project Owner
Project A Project A
Project B Bertha Thomas
Project C Jane Smith
Project D Project D

I've also tried every way to use loc I could think of, and I'm just lost. The above is the closest I've gotten. Any ideas would be appreciated, and don't hesitate to let me know if I need to post more code.

Thanks!