【问题标题】:Recursively find keypair relationships in python list/df在python list/df中递归查找密钥对关系
【发布时间】:2021-12-25 06:45:53
【问题描述】:

我正在尝试从 python 中的 500 万个列表中解析整数对。

它们表示记录网络的成对关系。

我相信递归将是解决此问题的方法,但我找不到好的例子或正确的术语来描述问题。

我想要

  • 遍历关系两边的每条记录
  • 遍历所有其他亲属到两边的每条记录
  • 将所有找到的记录合并到一个组下(列表、字典、最简单的),以便我可以为它们分配记录 ID
import pandas as pd

df_list = [[5213728 ,7381649],
           [2538095 ,5213728],
           [5213728 ,8163900],
           [3453455 ,3434644]
           ]
df_cols = ['MATCHED_KEY','SKEY']

#build a list of unique records
masterlist = pd.concat([pd.DataFrame(df['SKEY'].drop_duplicates()),pd.DataFrame(df['MATCHED_KEY'].drop_duplicates().rename('SKEY'))])


for idx,row in masterlist.iterrows():
    k = row['SKEY']

    #I imagine the next step is to go back through the df and keep adding more keys from both sides to a list until I've exhausted all links, then remove them from my master list and continue...

理想的输出应该是这样的:

{ 1: [2538095, 5213728,7381649, 8163900],
  2: [3453455, 3434644 ]
}

但只要找到所有相关记录并将它们分组就足够了

【问题讨论】:

    标签: python python-3.x pandas recursion


    【解决方案1】:

    你的情况是networkx

    import networkx as nx 
    G = nx.from_pandas_edgelist(df, 'MATCHED_KEY', 'SKEY')
    l = list(nx.connected_components(G))
    d = dict(zip(range(len(l)), l))
    d
    {0: {5213728, 7381649, 8163900, 2538095}, 1: {3434644, 3453455}}
    

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2014-04-29
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多