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

绘制K-means散点图时报错'DataFrame' object has no attribute 'label'如何解决

问题根因

这个报错是两个问题叠加导致的:

  1. 执行完K-means聚类后,你没有将生成的聚类标签写入DataFrame的label列,调用df.label时pandas找不到对应属性
  2. 现有DataFrame的消费列名是PURCHASES,绘图代码里写的PURCHASE少了末尾的S,后续也会触发列不存在的报错
解决步骤
  • 第一步:将K-means的聚类结果写入DataFrame
    假设你已经完成K-means模型训练,执行以下代码新增label列:
    df['label'] = kmeans.labels_
    
  • 第二步:修正绘图代码里的列名错误,把所有df["PURCHASE"]改成df["PURCHASES"]
  • 第三步:重新运行绘图代码即可
修正后完整绘图代码
plt.scatter(df["BALANCE"][df.label == 0], df["PURCHASES"][df.label == 0],s=80,c='magenta',label='Careful')
plt.scatter(df["BALANCE"][df.label == 1], df["PURCHASES"][df.label == 1],s=80,c='yellow',label='Standard')
plt.scatter(df["BALANCE"][df.label == 2], df["PURCHASES"][df.label == 2],s=80,c='green',label='Target')
plt.scatter(df["BALANCE"][df.label == 3], df["PURCHASES"][df.label == 3],s=80,c='cyan',label='Careless')
plt.scatter(df["BALANCE"][df.label == 4], df["PURCHASES"][df.label == 4],s=80,c='burlywood',label='Sensible')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red', label = 'Centroids')
plt.title('Customers Segmentation based on their Credit Card usage bhaviour')
plt.xlabel('BALANCE')
plt.ylabel('PURCHASES')
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:45:00