Home > other >  Select rows from dataframe based on isclose() condition
Select rows from dataframe based on isclose() condition

Time:10-21

I have a dataframe orig_df with "Alpha" and "Method" column names.

num is a floating point number with some floating point error. For example, it is 1.1400000000000001.

Meanwhile, "Alpha" values are truncated to 1.14.

As a result, I want to return all the rows such that orig_df["Alpha"] and num are close (and that method matches some string method_type, but that's less relevant).

So far I have:

temp_df = orig_df[
                (math.isclose(orig_df["Alpha"], num))
                & (orig_df["Method"] == method_type)
            ]

But then i receive the error

TypeError: cannot convert the series to <class 'float'>

How can I fix this?

CodePudding user response:

math.isclose is not a function that can cooperate with pandas and numpy arrays.

You need numpy.isclose:

temp_df = orig_df[
                (np.isclose(orig_df["Alpha"], num))
                & (orig_df["Method"] == method_type)
            ]

np is numpy in this case.

  • Related