I have classified my data into several neighborhoods using k nearest neighbors. I need to efficiently calculate the mean and standard deviation for all features of data points belonging to a particular neighborhood. I am using sklearn.kneighbors.

  • $\begingroup$ Do you want the spatial mean and standard deviation? Like the average in each dimension of the position? $\endgroup$
    – JahKnows
    Mar 12, 2019 at 23:42

1 Answer 1


If you append the predicted neighbourhood onto your data df (let's call this neighbourhood), then using groupby and transform within a loop should do the trick.

As an example:

features = [var_1,var_2,...] # a list of the features to run over
for col in features:
  df[col+'_mean'] = df.groupby('neighbourhood')[col].transform('mean')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.