python - Pandas 匹配 URL 列表以检查依赖关系
问题描述
从 URL 列表中,我想检查 complete_path 中的每个值是否是另一行的子文件夹。
子文件夹的标准是:
- 子文件夹以父行 URL 的 URL 开头并完全包含
- 子文件夹的反斜杠 \ 数量比父文件夹多。
这是我的熊猫数据框示例。
ID complete_path
1 Ajax
2 Ajax\991\1
3 Ajax\991
4 BVB
5 BVB\Christy
6 BVB_Christy
这是我的输出示例
ID complete_path dependency
1 Ajax None
2 Ajax\991\1 1,3
3 Ajax\991 1
4 BVB None
5 BVB\Christy 4
6 BVB_Christy None
解决方案
这听起来像一个网络问题。networkx
很有帮助。
import networkx as nx
new_df = (df.assign(path=df.complete_path.str.split('\\'))
.explode('path')
)
base = new_df.duplicated('ID', keep='last')
new_df['path_id'] = new_df['path'].map(new_df.loc[~base].set_index('path')['ID'])
# create the graph
G = nx.from_pandas_edgelist(new_df, source='path_id',target='ID', create_using=nx.DiGraph)
df['dependency'] = [nx.ancestors(G,i) or None for i in df['ID']]
输出:
ID complete_path dependency
0 1 Ajax None
1 2 Ajax\991\1 {1, 3}
2 3 Ajax\991 {1}
3 4 BVB None
4 5 BVB\Christy {4}
5 6 BVB_Christy None
推荐阅读
- python - 在条件语句中使用时间作为参数
- visual-studio-code - 无法使用 html 文件将样式应用于 VSCode Webview
- ubuntu - Meteor Svelte 找不到我在 Ubuntu 上创建的文件
- ubuntu - 如何使用 udev 规则自动挂载 USB 块设备?
- travis-ci - 在 GitHub 操作上使用 dpl
- java - 三星键盘退格键不适用于 SearchView
- php - 如何以智能的方式使用 PHP PDO 显示来自 PostgreSQL 的图像
- java - 尽管是数学,但代码打印你好世界
- apache-spark - 在 k8s 集群中 Spark 提交失败
- java - Spring将实体管理器getResultList结果转换为JSON