Function reads np.array - produces the mean for k nn to number p in np.array

2024/10/11 6:29:08

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 = 3In this case, I would need to generate the mean for ([11, 12, 10)]
as they are closest to p = 15

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.

Thanks in advance.

Answer

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])

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])

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
https://en.xdnf.cn/q/118358.html

Related Q&A

How to plot a line over a bar chart

I am trying to plot a line over a bar chart, but when I plotted the line the bar chart disappeared - and so did my x index values. Can anyone help me plot the line and the bar in the same figure? Than…

How to trim spaces between list elements in an f-string? [duplicate]

This question already has answers here:Print all items in a list with a delimiter(8 answers)Closed 2 months ago.I have a string I am formatting and printing lists using f-string and I need to eliminate…

Keeping name and score together while sorting

so I need to sort some high scores into order and here is the code I already have:def sortscores():namelist = []scorelist = []hs = open("hst.txt", "r")hscounter = 0for line in hs:if…

How to put values of pandas dataframe into a for loop in python?

This is a part of a Python API Connection program Here is the DataFrame SampleRegion Sector Brand ID Start Date 7188 US 41 40000 2006-03-06 7189 US 41 40345 2017-11-06 …

Partition Array

Given an array nums of integers and an int k, partition the array (i.e move the elements in nums) such that: All elements < k are moved to the left. All elements >= k are moved to the right Retur…

Tensorflow model accuracy

My model which I have trained on a set of 29K images for 36 classes and validated on 7K images. The model has a training accuracy of 94.59% and validation accuracy of 95.72% It has been created for OCR…

python email.message_from_string() parse problems

My setup uses fetchmail to pull emails from Gmail, which are processed by procmail and passes it to a python script.When I use email.message_from_string(), the resulting object is not parsed as an emai…

Python: Function returning highest value in list without max()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 7…

Given edges, how can find routes that consists of two edges in a vectorised way?

I have an array of towns and their neighbours. I want to get a set all the pairs of towns that have at least one route that consists of exactly two different edges. Is there a vectorized way to do this…

Usefulness of one-line statements in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…