从 excel 文件中读取数据进行分析

Read data from excel file for analysis

我有以下两段代码和excel文件。我只是不明白如何组合它们,以便我可以从 excel 文件中读取并使用这些数字形成一个簇。

import matplotlib.pyplot as plt
import xlrd
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans

fileWorkspace = 'C://Users/bob/Desktop/'

pull=[]
wb1 = xlrd.open_workbook(fileWorkspace + 'try.xlsx')
sh1 = wb1.sheet_by_index(0)

for a in range(0,sh1.nrows):
    for b in range(0,sh1.ncols):
        pull.append(sh1.cell(a,b).value)
    print('Finished in row' + str(a))


x = [11,19,23,33,44,91,92,90,60,63]

y = [92,85,22,25,86,78,63,51,66,15]


X = [list(item) for item in zip(x,y)]

kmeans = KMeans(n_clusters=3)
kmeans.fit(X)

centroids = kmeans.cluster_centers_
labels = kmeans.labels_

print(centroids)
print(labels)

colors = ["g.","r.","y.","c.","m.","k."]

for i in range(len(X)):
    print("coordinate:",X[i], "label:", labels[i])
    plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)

plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths=5, zorder=10)
plt.show()

excel文件图片:

这很复杂,因为我必须读取那一行数据,然后进行聚类。我还必须跳过行和列才能阅读它们。

如果您不反对使用 pandas you can use the read_excel 功能,请执行以下操作:

import pandas as pd
# Read in data from first sheet
df = pd.read_excel(filename, sheetname=0, parse_cols='B:D', index_col=0, header=[0,1])

这样您就可以同时处理空白列以及 header 和数据标签。从那里您可以通过 df.values 以 numpy 数组的形式访问数据,或者通过执行以下操作获取列表 (y, x) 对的列表:

pairs = df.values.tolist()

您还可以通过使用适当的范围遍历行 and/or 列来使用 xlrd。例如,如果您只想将示例文件中的数据读入列表列表中,您可以执行以下操作:

import xlrd

workbook = xlrd.open_workbook(filename)
sheet = workbook.sheet_by_index(0)

pairs = []
# Iterate through rows starting at the 3rd row)
for i in range(2, 15):
    # Iterate through columns starting at the 3rd column
    pairs.append([sheet.cell(i, j).value for j in range(2, 4)])

在 xlrd 中可能有更好的方法来执行此操作,但我很少使用它。