python - Is there a way to vectorize this loop -


is there way vectorize code eliminate loop:

import numpy np z = np.concatenate((x, labels[:,none]), axis=1) centroids = np.empty([len(unique(labels))-1,2]) in unique(labels[labels>-1]):     centroids[i,:]=z[z[:,-1]==i][:,:-1].mean(0) centroids 

this code produces pseudo centroids dbscan scikit-learn example, in case want play find vectorized form, i.e. x , labels defined in example.

thanks help!

you can use bincount() 3 times:

count = np.bincount(labels) x = np.bincount(labels, x[:, 0]) y = np.bincount(labels, x[:, 1])  centroids = np.c_[x, y] / count[:, none] print centroids 

but if can use pandas, simple:

z = np.concatenate((x, labels[:,none]), axis=1) df = pd.dataframe(z, columns=("x", "y", "label")) df[df['label']>-1].groupby("label").mean() 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -