How to conditionally update DataFrame column in Pandas

PythonPandas

Python Problem Overview


With this DataFrame, how can I conditionally set rating to 0 when line_race is equal to zero?

    line_track  line_race  rating foreign
 25        MTH         10     84    False
 26        MTH          6     88    False
 27        TAM          5     87    False
 28         GP          2     86    False
 29         GP          7     59    False
 30        LCH          0    103     True
 31        LEO          0    125     True
 32        YOR          0    126     True
 33        ASC          0    124     True

In other words, what is the proper way on a DataFrame to say if ColumnA = x then ColumnB = y else ColumnB = ColumnB

Python Solutions


Solution 1 - Python

df.loc[df['line_race'] == 0, 'rating'] = 0

Solution 2 - Python

Use numpy.where to say if ColumnA = x then ColumnB = y else ColumnB = ColumnB:

df['rating'] = np.where(df['line_race']==0, 0, df['rating'])

Solution 3 - Python

I have always used method given in Selected answer, today I faced a need where I need to Update column A, conditionally with derived values. the accepted answer shows "how to update column line_race to 0. Below is an example where you have to derive value to be updated with:

df.loc[df['line_race'].isna(), 'rating'] = ( (df['line_race'] - df['line_race2'])/df['line_race2'] )

Using this you can UPDATE dynamic values ONLY on Rows Matching a Condition.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTravisVOXView Question on Stackoverflow
Solution 1 - PythonViktor KerkezView Answer on Stackoverflow
Solution 2 - PythonSpeedCoder5View Answer on Stackoverflow
Solution 3 - Pythonsumon cView Answer on Stackoverflow