【问题标题】:Cluster Matrix from CSV Pandas DF Scipy来自 CSV Pandas DF Scipy 的聚类矩阵
【发布时间】:2018-04-18 03:59:46
【问题描述】:

我对 pandas 很陌生,对 scipy 聚类完全陌生。我有一个使用 pd.read_csv 读取的熊猫数据框,它是一个看起来像这样的矩阵(值表示彼此之间的距离:

    dog cat squ mea  che 
dog  0  .6  .5  .3    .2 
cat  1   0  .3  .7    .9
squ .6  .3   0  .3    .8    
mea .1  .1  .3   0    .9
che .4  .3  .4  .7     0

我想使用 scipy 对我的矩阵进行聚类,以最终创建一个具有层次/凝聚聚类的树状图,我尝试了

from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
Z = linkage(df)

但我立即遇到此值错误,不知道如何继续

ValueError: could not convert string to float: "'dog'"

我知道我没有正确地对这些矩阵进行聚类,但不确定如何继续。

【问题讨论】:

    标签: python pandas matrix scipy cluster-computing


    【解决方案1】:

    只要第一列是索引,您的代码就很适合我。加载数据框时,像这样加载它,指定index_col=[0] 将第一列指定为索引:

    df = pd.read_csv(..., index_col=[0])
    

    df
    
         dog  cat  squ  mea  che
    dog  0.0  0.6  0.5  0.3  0.2
    cat  1.0  0.0  0.3  0.7  0.9
    squ  0.6  0.3  0.0  0.3  0.8
    mea  0.1  0.1  0.3  0.0  0.9
    che  0.4  0.3  0.4  0.7  0.0
    
    Z = linkage(df)
    Z
    
    array([[ 0.        ,  4.        ,  0.678233  ,  2.        ],
           [ 2.        ,  3.        ,  0.69282032,  2.        ],
           [ 1.        ,  6.        ,  0.71414284,  3.        ],
           [ 5.        ,  7.        ,  0.93808315,  5.        ]])
    
    dendrogram(Z)
    
    plt.show()
    

    【讨论】:

    • 天哪!我忽略了将第一列指定为索引。非常感谢,很高兴终于看到我的数据可视化。将来在读取矩阵时肯定会更加关注指定索引的重要性。
    猜你喜欢
    • 2012-05-23
    • 2017-03-16
    • 2019-07-10
    • 2013-07-23
    • 2018-08-05
    • 2013-10-10
    • 2016-03-14
    • 2016-01-24
    • 2015-06-21
    相关资源
    最近更新 更多