Comparing floats in a pandas column

前端 未结 3 1863
一生所求
一生所求 2020-12-09 02:44

I have the following dataframe:

       actual_credit    min_required_credit
   0   0.3              0.4
   1   0.5              0.2
   2   0.4              0         


        
相关标签:
3条回答
  • 2020-12-09 03:19

    Due to imprecise float comparison you can or your comparison with np.isclose, isclose takes a relative and absolute tolerance param so the following should work:

    df['result'] = df['actual_credit'].ge(df['min_required_credit']) | np.isclose(df['actual_credit'], df['min_required_credit'])
    
    0 讨论(0)
  • 2020-12-09 03:38

    Use pandas.DataFrame.abs() instead of the built-in abs():

    df['result'] = df['actual_credit'].abs() >= df['min_required_credit'].abs()
    
    0 讨论(0)
  • 2020-12-09 03:42

    In general numpy Comparison functions work well with pd.Series and allow for element-wise comparisons: isclose, allclose, greater, greater_equal, less, less_equal etc.

    In your case greater_equal would do:

    df['result'] = np.greater_equal(df['actual_credit'], df['min_required_credit'])
    

    or alternatively, as proposed, using pandas.ge(alternatively le, gt etc.):

    df['result'] = df['actual_credit'].ge(df['min_required_credit'])
    

    The risk with oring with ge (as mentioned above) is that e.g. comparing 3.999999999999 and 4.0 might return True which might not necessarily be what you want.

    0 讨论(0)
提交回复
热议问题