python - 仅使用特定 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
解决方案
当您在问题中运行以下命令时
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
推荐阅读
- nginx - 为什么我的网站被下载而不是运行?
- polymer-3.x - Lit-Element - 无法从对象中获取项目 ID
- sql - 在两个日期之间添加行 Presto
- python - SQLite Python:插入默认值(时间戳)
- git - 如何在 Windows 中使用 git bash nano 终端向 github 进行身份验证?
- html - 对齐某些东西但保持响应的最佳方法是什么
- elixir - 如果没有在 Elixir 中进行元编程,就无法推断出这个“print_block”定义执行的确切行号吗?
- reactjs - Reactjs隐藏和取消隐藏切换按钮上的所有记录单击
- c++ - MFC CComboBoxEx GDI 资源泄漏
- ios - 为登录页面 iOS Swift 4 设置约束的正确方法是什么?