【问题标题】:KMeans Clustering only using specific Csv column仅使用特定 Csv 列的 KMeans 聚类
【发布时间】:2020-05-13 16:40:03
【问题描述】:

按照教程,我正在学习如何使用 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

【问题讨论】:

  • 一个原因是,在您的“Column_1”数据集中,可能存在一些无法转换为浮点数的垃圾数据。
  • @N.Moudgil,数据很好。它只是数字,而其中一些可能是小数
  • 在您的代码中:我猜 X=pd.DataFrame([['Column_1']]) 是一个错误。您是否尝试过 X=df[['Column_1']] 之类的方法?
  • @Louis Hulot,我收到错误消息说ValueError: could not convert string to float: '3352,4'
  • 我认为您没有正确读取 csv(,是 csv 文件中的默认分隔符)。将它放在字符串中并不常见。您能否显示类似 df.head() 的内容,以便我们知道您的数据中有什么?

标签: python pandas csv k-means


【解决方案1】:

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

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(',','.')

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

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

【讨论】:

  • 我试过 X=df[['your_first_col_name']] 但我收到错误 ValueError: could not convert string to float: '525,4' 。我认为这可能是因为该列中的某些值是小数
  • 是的,小数和它们之间有,,您应该使用.replace() 方法删除那些。我只是说十进制,因为上面的错误, 是最后。
  • 我已经添加了当我打印头部时输出的样子。你能帮我看看如何在代码中实现这个
  • 如果我像这样X=df['Column_1']=df['Column_1'].str.replace(',','.') 使用您的更新答案。我收到错误消息说ValueError: Expected 2D array, got 1D array instead:
  • @mandi 这是与 K-Means 和缩放相关的另一个问题,您必须在发生错误时分享完整的详细信息或开始另一篇与之相关的帖子
猜你喜欢
  • 2019-08-05
  • 2019-11-19
  • 2015-02-26
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2015-02-05
  • 2019-11-27
  • 2013-11-18
相关资源
最近更新 更多