Search code examples
pythonpandasnumpyfloating-pointequality

Comparing two pandas series for floating point near-equality?


I can compare two Pandas series for exact equality using pandas.Series.equals. Is there a corresponding function or parameter that will check if the elements are equal to some ε of precision?


Solution

  • You can use numpy.allclose:

    numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
    

    Returns True if two arrays are element-wise equal within a tolerance.

    The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

    numpy works well with pandas.Series objects, so if you have two of them - s1 and s2, you can simply do:

    np.allclose(s1, s2, atol=...) 
    

    Where atol is your tolerance value.