python - 如何创建时间重叠的邻接矩阵?

标签 python r pandas dplyr networkx

考虑这个简单的例子

#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]间隔重叠,则两个节点之间存在一条边。

有没有一种有效的方法可以从输入数据中生成邻接矩阵边缘列表,以便我可以在网络包(例如)中使用它>networkx?我的真实数据集比这大得多。

谢谢!

最佳答案

我认为这是制作邻接矩阵的可能解决方案。这个想法是对每个时隙进行相互比较,然后通过顶点组减少比较。

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

关于python - 如何创建时间重叠的邻接矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176865/

相关文章:

python - pandas.DatetimeIndex.snap 时间戳左出现频率

python - 更有效的方法是将 pandas 数据框中的列子集居中并保留列名

python - urls.py 中的 Django EOL

python - Pandas:追加现有的 CSV 文件、额外的列

r - 使用 R 从另一个表创建新的重复表,从原始表中添加新值

java - 在 "upgrading"到 OSX Yosemite 之后,RStudio/R 中的 rJava 加载错误

python - Taipy:没有显示图表,可能是由于行中的 "Invalid tag name ' 文本”

python - 以单个下划线字符结尾的字符串

python - 如何在运行时更改工具栏中 Action 的图标?

r - 使用 tidyr 在 R 中将行拆分为列