根据最大值将列表值分组

时间:2020-07-21 12:47:03

标签: python scikit-learn cluster-analysis k-means

如果我有一个数组(X),我正在研究k均值算法以对数字列表进行聚类

X=array([[0.85142858],[0.85566274],[0.85364912],[0.81536489],[0.84929932],[0.85042336],[0.84899714],[0.82019115], [0.86112067],[0.8312496 ]])

然后我运行以下代码

from sklearn.cluster import AgglomerativeClustering

cluster = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')
cluster.fit_predict(X)

for i in range(len(X)):
    print("%4d " % cluster.labels_[i], end=""); print(X[i])

我得到了结果

   1     1  [0.85142858]
   2     3  [0.85566274]
   3     3  [0.85364912]
   4     0  [0.81536489]
   5     1  [0.84929932]
   6     1  [0.85042336]
   7     1  [0.84899714]
   8     0  [0.82019115]
   9     4  [0.86112067]
   10    2  [0.8312496]

如何在(i)值的每个群集中获取最大数量?像这样

0: 0.82019115   8
1: 0.85142858   1
2: 0.8312496    10
3: 0.85566274   2
4: 0.86112067   9

1 个答案:

答案 0 :(得分:1)

首先使用zip将它们成对分组,然后按值(对的第二个元素)对它们进行升序排序,并从中创建字典。

尝试:

res =  list(zip(cluster.labels_, X))
max_num = dict(sorted(res, key=lambda x: x[1], reverse=False))

最大数量:

{0: array([0.82019115]),
 2: array([0.8312496]),
 1: array([0.85142858]),
 3: array([0.85566274]),
 4: array([0.86112067])}

编辑:

你想要这个吗?

elem = list(zip(res, range(1,len(X)+1)))
e = sorted(elem, key=lambda x: x[0][1], reverse=False)
final_dict = {k[0]:(k[1], v) for (k,v) in e}
for key in sorted(final_dict):
    print(f"{key}: {final_dict[key][0][0]} {final_dict[key][1]}")

0: 0.82019115 8
1: 0.85142858 1
2: 0.8312496 10
3: 0.85566274 2
4: 0.86112067 9

OR

import pandas as pd    
df = pd.DataFrame(zip(cluster.labels_,X))
df[1] = df[1].str[0]
df = df.sort_values(1).drop_duplicates([0],keep='last')
df.index = df.index+1
df = df.sort_values(0)

df:

    0   1
8   0   0.820191
1   1   0.851429
10  2   0.831250
2   3   0.855663
9   4   0.861121