0

I have two arrays.

org_df = [2732.64, 2296.35, 1262.28, 567.6, 436.29, 262.98, 238.74, 210.38,19]
calc_df = [19, 2296.34, 436.3, 2732.64]

I want to compare these arrays and create a new array with the same elements and with 0.01 tolerance.

new_list = [2732.64, 2296.35 ,436.29,19]

I added the code but it doesn't work:

picture showing code

1
  • In your code, your if statement is always true, as the absolute difference is always >=0.01 or <= 0.01 Commented Nov 28, 2021 at 22:31

4 Answers 4

1

You can do it with numpy module's isclose function.

new_list = [i for i in org_df if np.any(np.isclose(i, calc_df, atol=0.01))]
Sign up to request clarification or add additional context in comments.

Comments

1

If you use numpy:

org_df = np.array([2732.64, 2296.35, 1262.28, 567.6, 436.29, 262.98, 238.74, 210.38,19])
calc_df = np.array([19, 2296.34, 436.3, 2732.64])

new_list = org_df[np.any(np.abs(org_df - calc_df[:, None]) <= 0.01, axis=0)]
print(new_list)

# Output:
array([2732.64, 2296.35,  436.29,   19.  ])

Comments

1

If you do not want to use a dependency like numpy, you can do this using list comprehension and pythons awesome range comparison. Python is pretty neat for this!

diff = abs(tolerance)
new_list = [y for x in org_df for y in calc_df if (y-diff <= x <= y+diff)]

Gives the exact result. Though it might be slower than a numpy array.

Comments

0

To avoid adding a dependency like numpy, you need to iterate through both lists and do something like this:

new_list = []
for a in org_df:
    for b in calc_df:
        if -0.01 < a - b < 0.01:
            new_list.append(a)

And if you want to use list comprehension instead, use this one liner:

new_list = [a for a in org_df for b in calc_df if -0.01 < a - b < 0.01]

2 Comments

thanks for your help but this method only selects same values
I'm not sure I understood your question then, this subtracts the values and adds them to new_list if they are within a tolerance. For your dummy data, I get the result you asked for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.