先说几句话。首先,之后模型.拟合(十) 可以使用访问所有标签model.labels\. 模型.预测()可用于预测新数据上的标签。其次,除非您确定不需要模型来对新数据进行预测,否则函数最好也返回实际模型。在
同样,对于您的问题,您可以将预测的标签附加到原始数据帧,然后按如下所示的子集将结果分配给新的数据帧,或者使用其他方法(如.groupby()来分析各个簇)。在import pandas as pd
from sklearn.cluster import KMeans
import numpy as np
# Data
X = np.array([[1, 2], [1, 4], [1, 0],
[4, 2], [4, 4], [4, 0]])
df = pd.DataFrame(X, columns = ['x', 'y'])
def doKmeans(X, nclust):
model = KMeans(nclust)
model.fit(X)
return (model.labels_, model.cluster_centers_)
clust_labels, cent = doKmeans(X, 2)
df['label'] = clust_labels
df
df[df['label'] == 1]
df
Out[26]:
x y
0 1 2
1 1 4
2 1 0
3 4 2
4 4 4
5 4 0
df['label'] = clust_labels
df
Out[27]:
x y label
0 1 2 1
1 1 4 1
2 1 0 0
3 4 2 0
4 4 4 1
5 4 0 0
df[df['label'] == 1]
Out[28]:
x y label
0 1 2 1
1 1 4 1
4 4 4 1