假设我有k个标量列,并且我想将条目分组,如果它们沿着每列彼此之间的距离在一定范围内
假设simpicity k为2,它们是我唯一的列
pd.DataFrame(list(zip(sorted(choices(range(0,10), k=20)), choices(range(20,29), k=20))), columns=['a','b'])
屈服
[(1, 27),
(1, 27),
(1, 21),
(2, 23),
(3, 25),
(4, 23),
(4, 28),
(4, 27),
(4, 22),
(4, 24),
(5, 26),
(6, 21),
(7, 26),
(7, 20),
(8, 24),
(8, 25),
(8, 23),
(9, 20),
(9, 28),
(9, 21)]
我需要分组,以便分组包括a
列中最多相隔m
的条目和b
列中最多相隔n
的条目。如果m
=n
=1,则集群将为:
(1, 27), (1, 27)
(1, 21)
(2, 23)
(3, 25), (4, 23), (4, 22), (4, 24)
(4, 28), (4, 27), (5, 26)
(6, 21), (7, 20)
(7, 26), (8, 24), (8, 25), (8, 23)
(9, 20), (9, 21)
(9, 28),
实现这一点的一种方法是使用pdist,但这不是一个好的解决方案,因为:
我相信这可能是一个非常相关的问题,但它没有一个普遍的答案:
一种可能帮助您找到答案的方法的草图:
a, b, c, d, e = tee(range(10), 5)
next(b, None)
next(c, None);next(c, None)
next(d, None);next(d, None);next(d, None)
next(e, None);next(e, None);next(e, None);next(e, None)
list(zip(a, b, c, d, e))
[(0, 1, 2, 3, 4),
(1, 2, 3, 4, 5),
(2, 3, 4, 5, 6),
(3, 4, 5, 6, 7),
(4, 5, 6, 7, 8),
(5, 6, 7, 8, 9)]
首先,我们用
metric = 'chebyshev'
做pdist
现在
c_mat
基本上是一个节点图,如果它们是<;每个方向都有一个间隔要找到完整的未连接图,在
networx
中可能有一个快速操作,但我将在numpy
中以稍微困难的方式进行操作,因为我不知道在那里要查找什么图论关键字现在
c_mat
是True
,如果有任何连接两行的链,out
是所有单独组的布尔索引。现在返回结果:您还可以使用这些布尔索引来访问原始
DataFrame
中的数据行编辑1:
现在,我们可以利用输入是半排序的这一事实来加快速度。但要做到这一点,我们需要
numba
现在我们需要将其加载到稀疏矩阵中
csr
做点积要快得多,所以c_mat = c_mat @ c_mat
可以工作,但停止条件中断。您可以使用Anreas K.的优秀答案here,也可以直接使用out = np.unique(c_mat.todense(), axis = 0)
编辑2:
在我解决这个问题之前,我无法从脑海中摆脱出来,除非我没有制作一个稠密的矩阵
也许有办法不用两个循环就能完成,但我无法摸索
你的问题让我想起了
lag
操作和cumsum
。这里有一个答案。如果您的数据很大,我认为使用pythonlist
和tuple
是可以的,默认模块必须有函数来完成我们的任务步骤1:获取数据
第2步:滞后1个长度
输出:
步骤3:定义custum函数,然后将观察结果分组
输出:
相关问题 更多 >
编程相关推荐