如何创建具有时间重叠的邻接矩阵?

2024-09-27 17:59:43 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑这个简单的例子

#python bros
pd.DataFrame({'id' : [1,1,2,3],
                       'time_in' : [0,30,1,5],
                       'time_out' : [2,35,3,6]})
Out[66]: 
   id  time_in  time_out
0   1        0         2
1   1       30        35
2   2        1         3
3   3        5         6


#R bros
dplyr::data_frame(id = c(1,1,2,3),
                  time_in = c(0,30,1,5),
                  time_out = c(2,35,3,6))

在这里,解释很简单。你知道吗

个体1在时间0和时间2之间停留在一个给定的地方。个体2停留在时间1和时间3之间。因此,个体2遇到了个体1,并在我的网络中连接到它。你知道吗

也就是说,我的网络的节点是id,如果两个节点的[time_in, time_out]间隔重叠,那么它们之间就有一条边。你知道吗

有没有一种有效的方法从这个输入数据中生成adjacency matrixedge list,这样我就可以在networkx这样的网络包中使用它?我真正的数据集远不止这些。你知道吗

谢谢!你知道吗


Tags: 数据in网络iddataframe节点time时间
1条回答
网友
1楼 · 发布于 2024-09-27 17:59:43

我认为这是一个可能的解决办法,使邻接矩阵。其思想是将每个时隙相互比较,然后通过顶点组减少比较。你知道吗

import numpy as np
import pandas as pd

df = pd.DataFrame({'id' : [1, 1, 2, 3],
                   'time_in' : [0, 30, 1, 5],
                   'time_out' : [2, 35, 3, 6]})
# Sort so equal ids are together
df.sort_values('id', inplace=True)
# Get data arrays
ids = df.id.values
t_in = df.time_in.values
t_out = df.time_out.values
# Graph vertices
vertices = np.unique(ids)
# Find time slot overlaps
overlaps = (t_in[:, np.newaxis] <= t_out) & (t_out[:, np.newaxis] >= t_in)
# Find vertex group slices
reduce_idx = np.concatenate([[0], np.where(np.diff(ids) != 0)[0] + 1])
# Reduce by vertex groups to make adjacency matrix
connect = np.logical_or.reduceat(overlaps, reduce_idx, axis=1)
connect = np.logical_or.reduceat(connect, reduce_idx, axis=0)
# Clear diagonal if you want to remove self-connection
i = np.arange(len(vertices))
connect[i, i] = False
# Adjacency matrix as data frame
graph_df = pd.DataFrame(connect, index=vertices, columns=vertices)
print(graph_df)

输出:

       1      2      3
1  False   True  False
2   True  False  False
3  False  False  False

相关问题 更多 >

    热门问题