首页 > 解决方案 > Pandas 匹配 URL 列表以检查依赖关系

问题描述

从 URL 列表中,我想检查 complete_path 中的每个值是否是另一行的子文件夹。

子文件夹的标准是:

这是我的熊猫数据框示例。

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

标签: pythonpandasnetworkxfeature-engineering

解决方案


这听起来像一个网络问题。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

推荐阅读