来自 CSV Pandas DF Scipy 的聚类矩阵
Cluster Matrix from CSV Pandas DF Scipy
我是 pandas 的新手,也是 scipy 集群的新手。我有一个 pandas 数据框,我使用 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 对矩阵进行聚类,最终创建具有 hierarchal/agglomerative 聚类的树状图,我尝试了
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
Z = linkage(df)
但我立即遇到此值错误,我不确定如何继续
ValueError: could not convert string to float: "'dog'"
我知道我没有正确聚类这些矩阵,但不确定如何继续。
只要第一列是索引,您的代码就很适合我。加载数据框时,像这样加载它,指定 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()
我是 pandas 的新手,也是 scipy 集群的新手。我有一个 pandas 数据框,我使用 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 对矩阵进行聚类,最终创建具有 hierarchal/agglomerative 聚类的树状图,我尝试了
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
Z = linkage(df)
但我立即遇到此值错误,我不确定如何继续
ValueError: could not convert string to float: "'dog'"
我知道我没有正确聚类这些矩阵,但不确定如何继续。
只要第一列是索引,您的代码就很适合我。加载数据框时,像这样加载它,指定 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()