函数读取np.array - 为np.array中的数字p生成k nn的均值 [英] Function reads np.array - produces the mean for k nn to number p in np.array

查看:248
本文介绍了函数读取np.array - 为np.array中的数字p生成k nn的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个读取numpy数组的函数,并为数组中的p个数生成k个最近点的均值。

I need to defina a function which reads a numpy array and produces the mean for k nearest points to number p in the array.

示例:

Example:

array= np.array([1, 2, 3, 4, 5, 6, 7, 50, 24, 32, 9, 11, 12, 10])
p= 15 (**Note this is not a number in the array, I will need to find the 
number closest to p or p number itself)
k = 3

In this case, I would need to generate the mean for ([11, 12, 10)]
as they are closest to p = 15

有了上述数字,我需要找出最接近于p的k个点的均值,p可以在数组中明确表示,或者可以不是。

With the above numbers, I will need to find the mean for k number of points closest to p and p can be explicitly stated in the array or may not be.

我是新人,在这一点上很困惑,觉得我已经耗尽了我的资源。我觉得这个问题之前已经被问过,但是对于我所需要的答案来说太复杂了。

I am new and very confused at this point and feel I have exhausted my resources. I feel this question has been asked before but the answers are much too complex for what I need.

在此先感谢。给定一个(1d)数组 arr 和标量输入<$()。

Thanks in advance.

推荐答案

c $ c> p ,以下是如何找到 n 最接近值的平均值:

Given a (1d) array arr and scalar input p, here's how you could find the mean of the n nearest values:

def neighbor_mean(arr, p, n=3):
    idx = np.abs(arr - p).argsort()[:n]
    return arr[idx].mean()

arr = np.array([1, 2, 3, 4, 5, 6, 7, 50, 24, 32, 9, 11, 12, 10])
neighbor_mean(arr, p=15)
# 11.0

在上面,首先你有绝对的区别:

In the above, first you take the absolute differences:

np.abs(arr - 15)
# array([14, 13, 12, 11, 10,  9,  8, 35,  9, 17,  6,  4,  3,  5])

然后 argsort()返回对数组排序的索引。我们感兴趣的是 n - 最小的绝对差异。这是你真正想要的,而不是直接对差异进行排序。

Then argsort() returns the indices that would sort an array. We're interested in the n-smallest absolute differences. This is what you're really looking for, rather than sorting the differences directly.

np.abs(arr - p).argsort()[:3]
# array([12, 11, 13])

最后,你想索引你的输入数组 arr ,并取其平均值:

Lastly you want to index your input array arr and take the mean of this:

arr[[12, 11, 13]]
# array([12, 11, 10])  # mean: 11.0

这篇关于函数读取np.array - 为np.array中的数字p生成k nn的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆