我有一个值数组
array = [100, 101, 102, 102.001, 103.2, 104.64, 106.368, 108.442]
值102
和102.001
应该相同。我想找到删除值102.001
而不是102
的最佳方法。
到目前为止,我有一个繁琐的方法来执行此操作,但是如果将数组反转,则会删除102
;
import numpy as np
array = [100, 101, 102, 102.001, 103.2, 104.64, 106.368, 108.442]
array_diff = np.ediff1d(array)
ai = np.array(np.where(array_diff<0.01))
array_out = np.delete(array,[ai[0][0]+1])
是否有一种方法可以合并/删除给定公差的值?
谢谢。
答案 0 :(得分:2)
香草python解决方案:
from itertools import groupby
def nearby_groups(arr, tol_digits=2):
# split up sorted input array into groups if they're similar enough
for (_, grp) in groupby(arr, lambda x: round(x, tol_digits)):
# yield value from group that is closest to an integer
yield sorted(grp, key=lambda x: abs(round(x) - x))[0]
array = [100, 101, 101.999, 102.001, 102, 103.2, 104.64, 106.368, 108.442]
print(list(nearby_groups(array)))
给予:
[100, 101, 102, 103.2, 104.64, 106.368, 108.442]
此解决方案假定输入已预先排序。