You need to enable JavaScript to run this app. Python如何基于相关系数矩阵对相似度≥70%的门店进行分组
优惠活动
大模型
产品
解决方案
定价
更多

Python如何基于相关系数矩阵对相似度≥70%的门店进行分组

实现思路

你要的是将相关系数≥0.7的门店归为同一组,本质是图的连通分量匹配逻辑:把每个门店看作节点,两个门店相关系数满足阈值就连一条边,最终同一个连通块内的所有门店属于同一组,间接关联的门店也会被自动分到同一组。

方法1:借助networkx实现(代码最简)

import pandas as pd
import networkx as nx

# 构造你给出的相关系数矩阵示例
data = {
    'store1': [1, 0.5, 0.65, 0.75, -0.35],
    'store2': [0.5, 1, 0.45, 0.8, 0.22],
    'store3': [0.65, 0.45, 1, 0.55, 0.85],
    'store4': [0.75, 0.8, 0.55, 1, 0.35],
    'store5': [-0.35, 0.22, 0.85, 0.35, 1]
}
corr_df = pd.DataFrame(data, index=['store1', 'store2', 'store3', 'store4', 'store5'])

threshold = 0.7
# 去掉自相关的对角线,生成邻接矩阵
adj_matrix = corr_df.mask(corr_df == 1, 0)
adj_matrix = adj_matrix[adj_matrix >= threshold].fillna(0)

# 建图取连通分量
G = nx.from_pandas_adjacency(adj_matrix)
groups = list(nx.connected_components(G))

# 输出结果
for idx, group in enumerate(groups, 1):
    print(f"第{idx}组:{list(group)}")

方法2:纯Python实现(无需第三方库,用并查集算法)

import pandas as pd

# 构造相关系数矩阵和方法1一致
data = {
    'store1': [1, 0.5, 0.65, 0.75, -0.35],
    'store2': [0.5, 1, 0.45, 0.8, 0.22],
    'store3': [0.65, 0.45, 1, 0.55, 0.85],
    'store4': [0.75, 0.8, 0.55, 1, 0.35],
    'store5': [-0.35, 0.22, 0.85, 0.35, 1]
}
corr_df = pd.DataFrame(data, index=['store1', 'store2', 'store3', 'store4', 'store5'])

# 并查集实现
class UnionFind:
    def __init__(self, nodes):
        self.parent = {n:n for n in nodes}
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    def union(self, x, y):
        rx, ry = self.find(x), self.find(y)
        if rx != ry:
            self.parent[ry] = rx

threshold = 0.7
stores = corr_df.index.tolist()
uf = UnionFind(stores)

# 只遍历上三角避免重复配对
for i in range(len(stores)):
    for j in range(i+1, len(stores)):
        if corr_df.iloc[i,j] >= threshold:
            uf.union(stores[i], stores[j])

# 整理分组结果
groups = {}
for s in stores:
    root = uf.find(s)
    groups.setdefault(root, []).append(s)

for idx, group in enumerate(groups.values(), 1):
    print(f"第{idx}组:{group}")

运行结果

两种方法的输出完全一致:

第1组:['store1', 'store2', 'store4']
第2组:['store3', 'store5']

如果需要调整阈值,直接修改threshold变量的数值即可。

内容的提问来源于stack exchange,提问作者Youssef Razak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 07:24:07