Replace Values in Pandas


Are you working with a DataFrame in pandas? Do you need to change some values in one of your columns? This would be similar to SQL’s UPDATE Table SET Column = WHERE statement.

Here is an article at Geeks for Geeks called How to Replace Values in Column Based on Condition in Pandas?

The general syntax is as follows. The DataFrame is called df.

df.loc[ df["col_name"] == "existing_value", "col_name"] = "new_value"

As an example, you may want to replace all negative values in a column of a pandas DataFrame with zeros. Perhaps the column contains a duration of time in minutes. You can’t have negative time in your duration column. You notice a few of these negative values in your DataFrame and you decide to correct for that.

df.loc[df['duration'] < 0, 'duration'] = 0 
df['duration'].min() # check that the minimum is now zero

In SQL, you can update a table’s column with a value under a certain condition. UPDATE table SET column = 0 WHERE column < 0; Here is a post at this website called SQL Update Statement.

Leave a comment

Your email address will not be published. Required fields are marked *