我有如下的餐厅销售数据,并希望找到彼此相关的餐厅。我正在寻找一种基于彼此相关性的聚类;其中“相关性”意味着“销售单位、收入和客流量的组合的最匹配/相似的餐厅”。(注:这是corelatedItems的后续问题)
+----------+------------+---------+----------+
| Location | Units Sold | Revenue | Footfall |
+----------+------------+---------+----------+
| Loc - 01 | 100 | 1,150 | 85 |
| Loc - 02 | 100 | 1,250 | 60 |
| Loc - 03 | 90 | 990 | 90 |
| Loc - 04 | 120 | 1,200 | 98 |
| Loc - 05 | 115 | 1,035 | 87 |
| Loc - 06 | 89 | 1,157 | 74 |
| Loc - 07 | 110 | 1,265 | 80 |
+----------+------------+---------+----------+发布于 2019-07-29 04:39:48
首先,将dataframe的索引设置为Location列,以便于索引
df1 = df1.set_index('Location')接下来,生成要比较的餐厅的所有组合:
import itertools
pairs = list(itertools.combinations(df1.index.values, 2))接下来,定义一个比较函数。让我们使用上一篇文章中使用的那个
import numpy as np
def compare_function(row1, row2):
return np.sqrt((row1['Units Sold']-row2['Units Sold'])**2 +
(row1['Revenue']- row2['Revenue'])**2 +
(row1['Footfall']- row2.loc[0, 'Footfall'])**2)接下来,遍历所有对并获得比较函数的结果:
results = [(row1, row2, compare_function(df1.loc[row1], df1.loc[row2]))
for row1, row2 in pairs]现在,您有了所有restuarant对的列表以及它们彼此之间的距离。
https://stackoverflow.com/questions/57238712
复制相似问题