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:
CodePudding user response:
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))]
CodePudding user response:
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. ])
CodePudding user response:
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.
CodePudding user response:
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]