Python 如何在数据帧上应用弯头方法

Python 如何在数据帧上应用弯头方法,python,pandas,k-means,Python,Pandas,K Means,我想应用弯头方法从下面的dataframe(df)样本中确定K个集群的数量,该样本有31行5列 col1,col2,col3,col4,col5 0.54,0.68,0.46,0.98,-2.14 0.52,0.44,0.19,0.29,30.44 1.27,1.15,1.32,0.60,-161.63 0.88,0.79,0.63,0.58,-49.52 1.39,1.15,1.32,0.41,-188.52 0.86,0.80,0.65,0.65,-45.27 我已经尝试了下面我在这里找到

我想应用弯头方法从下面的dataframe(df)样本中确定K个集群的数量,该样本有31行5列

col1,col2,col3,col4,col5
0.54,0.68,0.46,0.98,-2.14
0.52,0.44,0.19,0.29,30.44
1.27,1.15,1.32,0.60,-161.63
0.88,0.79,0.63,0.58,-49.52
1.39,1.15,1.32,0.41,-188.52
0.86,0.80,0.65,0.65,-45.27
我已经尝试了下面我在这里找到的:

但是,我收到错误消息“ValueError:x和y必须具有相同的第一维度,但具有形状(10,)和(1,)”


我做错了什么?

你的缩进在
wcss.append(kmeans.institute)
之后是不正确的,在链接文章中是正确的。将打印代码移出
for
循环。数据集中只有6个样本,不能计算超过6个集群。将示例数据的范围更改为
范围(1,7)
。我愚蠢的错误。非常感谢您指出它来明确错误(可能有助于您诊断是否再次发生类似事件):因为您在循环中有绘图代码,在
plt的第一次迭代中,绘图(范围(1,11),wcss)
wcss
只有一个值。所以,当你尝试绘图时,你有10个x值,只有1个y值。解释得很好。
def elbow_K():

    wcss = [] 
    for i in range(1, 11):
        
        kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=200, n_init=10, random_state=0)
        kmeans.fit(df)
        wcss.append(kmeans.inertia_)
        plt.plot(range(1, 11), wcss)
        plt.title('Elbow Method')
        plt.xlabel('Number of clusters')
        plt.ylabel('WCSS')
        plt.show()