How to conditionally update DataFrame column in Pandas

前端 未结 3 1692
挽巷
挽巷 2020-12-01 02:28

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

    line_track  line_race  rating fo         


        
相关标签:
3条回答
  • 2020-12-01 03:03
    df.loc[df['line_race'] == 0, 'rating'] = 0
    
    0 讨论(0)
  • 2020-12-01 03:20

    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.

    0 讨论(0)
  • 2020-12-01 03:25

    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'])
    
    0 讨论(0)
提交回复
热议问题