首页 > 解决方案 > 仅使用特定 Csv 列的 KMeans 聚类

问题描述

按照教程,我正在学习如何使用 Kmeans。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn.cluster import KMeans



X = np.array([[1, 2],
              [5, 8],
              [1.5, 1.8],
              [8, 8],
              [1, 0.6],
              [9, 11]])


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

centroids = kmeans.cluster_centers_
labels = kmeans.labels_

print(centroids)
print(labels)

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

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()

我想读取一个 csv 文件,然后使用其中一个数据框列来代替上面使用的数组。

我尝试了以下但我没有工作

df=pd.read_csv("Output.csv",encoding='latin1')
X=pd.DataFrame([['Column_1']]) 

我收到以下错误

ValueError: could not convert string to float: 'Column_1'

这是我使用时输出的样子df.head

    x    id  ... Column_name v      Column_1
0  25  0001  ...         NaN             854
1  28  0002  ...         NaN            85,4
2  29  0003  ...         NaN            1524
3  32  NaN   ...         NaN               0
4  85  0004  ...         NaN               0

标签: pythonpandascsvk-means

解决方案


当您在问题中运行以下命令时

X=pd.DataFrame([['Column_1']]) 

X 现在持有这个:

        0
0   Columns_1

错误很清楚,因为它说无法将 'Column_1' 转换为浮动,因为kmeans使用数字数据

你可以简单地选择你的第一列;

X=df[['your_first_col_name']]

编辑 要处理逗号,您可以使用:

df['Column_1']=df['Column_1'].str.replace(',','.')

另一种处理包含','而不是'.'像欧洲格式那样的小数的数据的方法是decimal在读取时声明参数csv ,如果原始数据是这样的:

A
1253
1253,5
12578,8
148,45
124589

我们可以将这些数据读取为

df=pd.read_csv('c2.csv', decimal=',')

输出将是

0      1253.00
1      1253.50
2     12578.80
3       148.45
4    124589.00
Name: A, dtype: float64

推荐阅读