首页 > 解决方案 > 集群 id 列中缺少值的问题

问题描述

我正在寻找一些关于如何在我的 df 中添加包含集群 id 的列的帮助(用于集群数据集的算法是 DBSCAN,我尝试了以下

# Compute DBSCAN

db = DBSCAN(eps=1, min_samples=30, algorithm='kd_tree', n_jobs=-1).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
np.sum(labels)
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_clusters_
n_noise_ = list(labels).count(-1)

print('Estimated number of clusters: %d' % n_clusters_)
print('Estimated number of noise points: %d' % n_noise_)
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(X, labels))
    df = df.join(pd.DataFrame(labels))
    df = df.rename(columns={0:'Cluster'})
    df.head

但我有一个看起来不合逻辑的问题。在聚类之前,我的数据集没有缺失值,而当我添加列(集群)时,clsuter=-1 用于噪声等,我也得到了缺失值(!),所以当我尝试清理我的数据集时,我没有任何选择,而不是排除 cluster=-1 和缺失值,这是我不想要的。你能帮我解决我的问题吗?

您可以找到包含问题的附加输出。聚类列中有大约 3000 个缺失值,我不明白这是怎么发生的。

输入额外列之前的数据集列有 38037 行。

任何评论都会有所帮助。

谢谢

缺失值问题

标签: pythoncluster-analysisoutliersdbscan

解决方案


您的df. 正如您在 Pandasjoin 文档中所读到的,如果on未指定参数:

调用者中的列或索引级别名称加入其他索引,否则加入索引上的索引。

所以,这样的事情正在发生:

labels
Out[66]: array([ 0,  0,  0,  1,  1, -1], dtype=int64)

# make dataframe that exactly matches labels
df = pd.DataFrame(labels, columns=['a'])

df
Out[68]: 
   a
0  0
1  0
2  0
3  1
4  1
5 -1

# change indices
df = df.set_index([pd.Index([0, 1, 3, 5, 7, 8])])

df
Out[70]: 
   a
0  0
1  0
3  0
5  1
7  1
8 -1

df.join(pd.DataFrame(labels))
Out[71]: 
   a    0
0  0  0.0
1  0  0.0
3  0  1.0
5  1 -1.0
7  1  NaN
8 -1  NaN

如果您不需要当前索引,我建议在 DBSCAN 之前重置索引:df.reset_index(drop=True, inplace=True).


推荐阅读