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 matrix
或edge list
输出这个输入数据,以便我可以在网络包中使用它,例如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
推荐阅读
- apache - IE 和 Edge 忽略 application/octet-stream MIME 类型
- javascript - 异步映射异步函数
- html - 如何使用变量创建适当的 iframe
- ruby-on-rails - 如何播放 Rails / Active Storage 提供的音频文件
- sql - 需要找出 SQL Server 表中的所有列是否具有相同的值
- gdb - gdb rbreak 和命令(或 dprintf 行为)?
- laravel - Laravel / Vue.js。在保存之前寻找图片编辑器来调整大小/裁剪
- android - 从后台颤振隔离向Android方法发送平台消息
- python - 如何检测 Pandas 时间序列图中的突然变化
- c# - 无法在 VS2017 Cummunity (V15.5.2) 上安装 Microsoft.Toolkit.Uwp.UI.Controls 5.0.0