如何有条件地更新熊猫中的 DataFrame 列

使用这个 DataFrame,当 line_race等于0时,我如何有条件地将 rating设置为0?

    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

换句话说,在 DataFrame 上,如果 ColumnA = x,那么 ColumnB = y else ColumnB = ColumnB 的正确表达方式是什么

124430 次浏览
df.loc[df['line_race'] == 0, 'rating'] = 0

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'])

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.