Python。列表索引必须是整数或片而不是tuple,因为没有一个索引可能是tup

2024-04-25 00:11:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python创建了excel,因此所有数据都是正确的: 以下是excel的代码:

import openpyxl as exl
import random


book = exl.load_workbook("test2.xlsx")
sheet = book.active


for x in range(1,50000):
    number = random.uniform(-100,100)

    mycell = sheet.cell(row = x, column = 4)
    mycell.value = number

for x in range(1,50000):
    number = random.uniform(-50,150)

    mycell = sheet.cell(row = x, column = 5)
    mycell.value = number


book.save('test2.xlsx')

然后我使用python分散excel中的所有点并应用集群。 我不明白我的列表在使用python创建时怎么会有任何错误,所以其中肯定没有错误。 以exl形式导入openpyxl 随机导入

import sklearn as skl
from sklearn.cluster import KMeans

import matplotlib.pyplot as plt
import math
import numpy as np

from sklearn.metrics import silhouette_score

book = exl.load_workbook("test2.xlsx")
sheet = book.active

coordinates = []

for row_var in range(2, sheet.max_row + 1):
    x = sheet.cell(row = row_var, column = 4).value
    y = sheet.cell(row=row_var, column = 5).value

    point = [x,y]
    coordinates.append(point)


kmeans = KMeans(init='k-means++', n_clusters=4, n_init=20).fit_predict(coordinates)
print(kmeans)
plt.scatter(coordinates[:,0], coordinates[:,1], c = kmeans, edgecolor = 'black')


score = silhouette_score(coordinates, kmeans)
print(score)


plt.grid()
plt.show()

Tags: importnumbervalueascellcolumnpltsheet
1条回答
网友
1楼 · 发布于 2024-04-25 00:11:05

这就是你出错的地方吗? plt.scatter(coordinates[:,0], coordinates[:,1])

如果是这样,我会尝试:

x_coord = [i[0] for i in coordinates]
y_coord = [i[1] for i in coordinates]
plt.scatter(x_coord, y_coord)

您将点存储为列表中的元组,而不是矩阵/数据帧类对象中的元组。:,0是试图用来访问列表中元素的元组。你知道吗

相关问题 更多 >