If I got it correctly, you just want to find the closest value from second dataframe.

masses = mass_q_sequence['Mass']
mass_pos = df_seq2['mass_pos']
# using broadcasting and finding indices of closest mass for each mass_pos:
closest_mass_indices = np.argmin(np.abs(masses.reshape(1, -1) - mass_pos.reshape(-1, 1)), axis=1) 
df['closest_mass'] = masses[closest_mass_indices]
Answer from dankal444 on Stack Overflow
Top answer
1 of 4
56

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:

Copydf['result'] = df['actual_credit'].ge(df['min_required_credit']) | np.isclose(df['actual_credit'], df['min_required_credit'])
2 of 4
10

@EdChum's answer works great, but using the pandas.DataFrame.round function is another clean option that works well without the use of numpy.

Copydf = pd.DataFrame(  # adding a small difference at the thousandths place to reproduce the issue
    data=[[0.3, 0.4], [0.5, 0.2], [0.400, 0.401], [0.2, 0.3]],
    columns=['actual_credit', 'min_required_credit'])

df['result'] = df['actual_credit'].round(1) >= df['min_required_credit'].round(1)
print(df)
Copy   actual_credit  min_required_credit  result
0            0.3                0.400   False
1            0.5                0.200    True
2            0.4                0.401    True
3            0.2                0.300   False

You might consider using round() to more permanently edit your dataframe, depending if you desire that precision or not. In this example, it seems like the OP suggests this is probably just noise and is just causing confusion.

Copydf = pd.DataFrame(  # adding a small difference at the thousandths place to reproduce the issue
    data=[[0.3, 0.4], [0.5, 0.2], [0.400, 0.401], [0.2, 0.3]],
    columns=['actual_credit', 'min_required_credit'])
df = df.round(1)
df['result'] = df['actual_credit'] >= df['min_required_credit']
print(df)
Copy   actual_credit  min_required_credit  result
0            0.3                  0.4   False
1            0.5                  0.2    True
2            0.4                  0.4    True
3            0.2                  0.3   False
🌐
W3Schools
w3schools.com › python › ref_math_isclose.asp
Python math.isclose() Method
The math.isclose() method checks whether two values are close to each other, or not.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 9457
assert_almost_equal / equals should allow access to np.allclose · Issue #9457 · pandas-dev/pandas
February 10, 2015 - I think a good intermediate step would be to check for array equivalence and then as a the second step call np.allclose--or maybe just do this on the outset. If that fails, which it will if there are any NaNs or if the tolerance is not met, then it will use the current logic. Or we could use np.isclose to consider NaNs as equivalent. https://github.com/pydata/pandas/blob/master/pandas/src/testing.pyx#L85 ·
🌐
GitHub
github.com › numpy › numpy › issues › 17846
np.isclose() raises an exception when used with pandas 1.0 Int64Dtype objects · Issue #17846 · numpy/numpy
August 27, 2020 - import pandas as pd # v1.0.5 import numpy as np # v1.19.4 df = pd.DataFrame({"a":[1,2,3],"b":[4,5,6]}) np.isclose(df.a,df.b) # output: array([False, False, False]) df.a = df.a.astype(pd.Int64Dtype()) df.b = df.b.astype(pd.Int64Dtype()) np.isclose(df.a,df.b) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-22-fe7c48482d30> in <module> ----> 1 np.isclose(df.a,df.b) <__array_function__ internals> in isclose(*args, **kwargs) /apps/python3/lib/python3.7/site-packages/numpy/core/numeric.py in isclose(a, b, rtol, at
Author   samredai
🌐
GitHub
github.com › rapidsai › cudf › issues › 5105
[FEA] Series or DataFrame support for equivalent of numpy.isclose · Issue #5105 · rapidsai/cudf
May 5, 2020 - >>> import cudf >>> s1 = cudf.Series([1.9876543, 2.9876654, 3.9876543]) >>> s2 = cudf.Series([1.987654321, 2.987654321, 3.987654321]) >>> rel_tol=1e-5 >>> abs_tol=0.0 >>> s2.isclose(s1, rel_tol, abs_tol) 0 True 1 True 2 True dtype: bool >>>
🌐
GitHub
gist.github.com › bmweiner › 1b7b837feb280057918ccd1e83f0898b
Compare equality of two pandas dataframes · GitHub
Compare equality of two pandas dataframes. GitHub Gist: instantly share code, notes, and snippets.
Top answer
1 of 1
7

I believe you need repeat columns values by numpy.broadcast_to before using numpy.isclose:

np.random.seed(142)

df = pd.DataFrame({'column':np.random.rand(10)})
print (df)
     column
0  0.902062
1  0.557808
2  0.655985
3  0.832471
4  0.199884
5  0.127254
6  0.771439
7  0.432289
8  0.385282
9  0.783643

A = [0.432, 0.783, 0.902]

#repeat by length of number of list A
len_A = len(A)
a = np.broadcast_to(df['column'].values[:, None], (len(df),len_A))
print (a)
[[0.90206152 0.90206152 0.90206152]
 [0.55780754 0.55780754 0.55780754]
 [0.65598471 0.65598471 0.65598471]
 [0.83247141 0.83247141 0.83247141]
 [0.19988419 0.19988419 0.19988419]
 [0.12725426 0.12725426 0.12725426]
 [0.77143911 0.77143911 0.77143911]
 [0.43228855 0.43228855 0.43228855]
 [0.38528223 0.38528223 0.38528223]
 [0.78364337 0.78364337 0.78364337]]

#pandas solution
m = pd.concat([df['column']] * len_A, axis=1)
print (m)
     column    column    column
0  0.902062  0.902062  0.902062
1  0.557808  0.557808  0.557808
2  0.655985  0.655985  0.655985
3  0.832471  0.832471  0.832471
4  0.199884  0.199884  0.199884
5  0.127254  0.127254  0.127254
6  0.771439  0.771439  0.771439
7  0.432289  0.432289  0.432289
8  0.385282  0.385282  0.385282
9  0.783643  0.783643  0.783643

m = np.isclose(a, b=A, atol=0.004)
print (m)
[[False False  True]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [ True False False]
 [False False False]
 [False  True False]]

Last get all values with True per rows by any:

print (m.any(axis=1))
[ True False False False False False False  True False  True]

And last filter by boolean indexing:

print (df[m.any(axis=1)])
     column
0  0.902062
7  0.432289
9  0.783643
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-math-library-isclose-method
Python math library | isclose() method - GeeksforGeeks
July 11, 2025 - Pandas · Practice · Django · Flask · Last Updated : 11 Jul, 2025 · In the Python math module, math.isclose() the method is used to determine whether two floating point numbers are close in value.
🌐
Codecademy
codecademy.com › docs › python › math module › .isclose()
Python | Math Module | .isclose() | Codecademy
July 25, 2024 - For example, the comparison 0.1 + 0.2 == 0.3 returns False, but using .isclose() would return True.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Check If the Floating Point Numbers Are Close in Python: math.isclose | note.nkmk.me
May 14, 2023 - You can write a comparison of floating point numbers like examples above simply by using the function isclose() in the math module.
🌐
Skytowner
skytowner.com › explore › numpy_isclose_method
NumPy | isclose method with Examples
February 22, 2022 - np.isclose(np.NaN, np.NaN, equal_nan=True) True · Published by Isshin Inada · Edited by 0 others · Did you find this page useful? thumb_up · thumb_down · Comment · Citation · Ask a question or leave a feedback... thumb_up · 0 · thumb_down · 0 · chat_bubble_outline · 0 · settings · Enjoy our search · Hit / to insta-search docs and recipes! Navigation Home Blog · Contact us · Resources Python Pandas MySQL Beautiful Soup Matplotlib NumPy PySpark ·
🌐
Stack Overflow
stackoverflow.com › questions › 72792602 › dataframe-index-with-isclose-function
indexing - Dataframe index with isclose function - Stack Overflow
I when using boolean I can get the index but when I try to use math.isclose the function does not work and gives an error. ... import pandas as pd df1 = pd.DataFrame({'col1':[0,.05,0.74,0.76,1], 'col2': [0, 0.05,0.5, 0.75,1], 'x1': [1,2,3,4,5], 'x2': [5,6,7,8,9]}) result75 = df1.index[round(df1['col2'],2) == 0.75].tolist() value75 = df1['x2'][result75] print(value75.mean())
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.isclose.html
numpy.isclose — NumPy v2.4 Manual
Unlike the built-in math.isclose, the above equation is not symmetric in a and b – it assumes b is the reference value – so that isclose(a, b) might be different from isclose(b, a).
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Interval.closed_right.html
pandas.Interval.closed_right — pandas 2.3.3 documentation
February 10, 2015 - Check if the interval is closed on the right side · For the meaning of closed and open see Interval
🌐
Educative
educative.io › answers › how-to-use-the-mathisclose-function-in-python
How to use the math.isclose() function in Python?
February 9, 2025 - In lines 2 and 3, we use the math.isclose() function to compare the two values.
🌐
TutorialsPoint
tutorialspoint.com › python-pandas-check-whether-the-interval-is-closed-on-the-left-side-right-side-both-or-neither
Python Pandas - Check whether the interval is closed on the left-side, right-side, both or neither
To check whether the interval is closed on the left-side, right-side, both or neither, use the interval.closed property. At first, import the required libraries −