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.
If you append the predicted neighbourhood onto your data
df (let's call this
neighbourhood), then using
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')