要找到接近给定目标集的numpy数组的元素,可以使用numpy库中的函数来实现。以下是一种可能的方法:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
target_set = np.array([2.5, 4.5, 6.5])
closest_indices = np.abs(arr[:, np.newaxis] - target_set).argmin(axis=0)
这里使用了广播机制将目标集扩展为与数组相同的维度,然后计算每个元素与目标集的差值的绝对值,并找到最小值的索引。
closest_elements = arr[closest_indices]
最终,closest_elements将包含与目标集中每个元素最接近的数组元素。
这种方法适用于一维数组。如果是多维数组,可以使用类似的方法,只需稍作修改即可。
对于numpy的更多详细信息和其他函数,请参考腾讯云的numpy产品介绍链接地址:https://cloud.tencent.com/document/product/845/20497
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云