You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用K-Means肘部法函数时df['']与df[['']]的传参差异及报错原因

报错原因及两者区别说明

1. 两种索引方式的核心差异

  • df['列名']返回的是一维Series对象,维度形状为(样本数,),仅具备行维度,没有特征维度的标识
  • df[['列名']]返回的是二维DataFrame对象,维度形状为(样本数, 1),符合特征矩阵的二维结构要求

2. 报错直接原因

Scikit-Learn框架下所有机器学习模型的fit方法,都要求输入的特征矩阵必须为二维结构,形状规范为(样本数量, 特征数量),不支持直接传入一维的Series或数组作为训练特征,因此传入df['列名']时会触发维度不匹配的报错。

3. 补充:你提供的代码存在的笔误修复

你贴出的代码目前还存在几处语法和调用错误,修复后可正常运行:

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def show_elbow(df):
    distance_list = []
    K = range(1, 9)
    for k in K:
        # 修复拼写错误:参数n_cluster改为n_clusters,变量名kmeams修正为kmeans
        kmeans = KMeans(n_clusters=k, max_iter=100)
        # 修复调用错误:改为调用实例的fit方法,而非KMeans类的静态方法
        kmeans.fit(df)
        distance_list.append(kmeans.inertia_)
    plt.plot(K, distance_list, 'bx-')
    plt.xlabel('聚类数量K')
    plt.ylabel('簇内平方和(Inertia)')
    plt.show()

如果需要直接使用一维Series作为输入,可手动转换为二维结构后传入:

show_elbow(df['列名'].values.reshape(-1, 1))

内容的提问来源于stack exchange,提问作者liuzx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:24:00