gpt4 book ai didi

python - 通过合并邻近的值来减少排序的数字列表的更好方法?

转载 作者:行者123 更新时间:2023-12-01 00:20:24 25 4
gpt4 key购买 nike

我有一个包含以下值的数字列表作为示例。

2, 99, 101, 150, 198, 201, 300

我们假设上面的数组总是按升序排序。

我的目标是对由变量x定义的彼此接近的值进行平均。假设 x = 5 预期结果应如下所示

2, 100, 150, 200, 300

以下是我编写的代码的工作副本

import statistics
def mean_reduce_by_proximity(data, distance):
new_data = []
temp = []
for val in data:
# if temp list is empty
if (len(temp) == 0):
temp.append(val)
# if temp list if not empty
else:
# Last item of temp list is in proximity to current value
if (val - temp[-1]) <= distance:
temp.append(val)
# Not in proximity
else:
temp_mean = round(statistics.mean(temp))
new_data.extend([temp_mean])
temp = []
temp.append(val)

# Handle last set of item(s)
if (len(temp) > 0):
temp_mean = round(statistics.mean(temp))
new_data.extend([temp_mean])
temp = []

return new_data

In[1]: mean_reduce_by_proximity([2, 99, 101, 150, 198, 201, 300], 5)
Out[1]: [2, 100, 150, 200, 300]

我的查询

  • 是否有针对此类减少的已知技术术语?
  • 流行的Python库中是否有内置函数可以做到这一点这个?

最佳答案

这是一种矢量化方法 np.add.reduceat -

def mean_reduce_by_proximity_vectorized(a, thresh):
# Get an array with indices off input array, such that each index
# represent start of a group of close proximity elements
i = np.flatnonzero(np.r_[True,np.diff(a)>thresh,True])

# Sum based on those indices. Hence, each group is summed.
sums = np.add.reduceat(a,i[:-1])

# Get counts of each group
counts = np.diff(i)

# Get average of each group and round those for final o/p
return np.round(sums/counts.astype(float))

示例运行 -

In [90]: a
Out[90]: array([ 2, 99, 101, 150, 198, 201, 300])

In [91]: mean_reduce_by_proximity_vectorized(a, thresh=5)
Out[91]: array([ 2., 100., 150., 200., 300.])

关于python - 通过合并邻近的值来减少排序的数字列表的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com