【问题标题】:Pandas Match list of URLs to check dependencyPandas 匹配 URL 列表以检查依赖关系
【发布时间】:2021-01-28 22:58:39
【问题描述】:

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

子文件夹的标准是:

  • 子文件夹以父行 URL 的 URL 开头并完全包含该 URL
  • 子文件夹的反斜杠 \ 计数比父文件夹多。

这是我的 pandas 数据框示例。

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

【问题讨论】:

    标签: python pandas networkx feature-engineering


    【解决方案1】:

    请尝试:

    import networkx as nx
    prepath = lambda x: x if not "\\" in x else "\\".join(x.split("\\")[:-1])
    df = df.assign(prepath = df["complete_path"].apply(prepath))
    df["source_ID"] = df["prepath"].map(df.set_index("complete_path")["ID"])
    g = nx.from_pandas_edgelist(df, source="source_ID", target="ID", create_using=nx.MultiDiGraph)
    df["dependency"] = [nx.ancestors(g,i) or None for i in df["ID"]]
    print(df[["ID","complete_path","dependency"]])
       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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 你好广!这给了我以下错误“仅适用于唯一索引值”。一旦我在第一行之后拆分我的数据集,new_df 就会爆炸并且有多行具有相同的索引值。
      猜你喜欢
      • 2023-03-16
      • 2018-09-04
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2017-09-23
      • 2023-03-25
      相关资源
      最近更新 更多