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
Post a Comment