代码之家  ›  专栏  ›  技术社区  ›  ℕʘʘḆḽḘ

获取网络邻接表的有效方法?

  •  0
  • ℕʘʘḆḽḘ  · 技术社区  · 7 年前

    pd.DataFrame({'id' : [1,1,2,3,4],
                  'place' : ['bar','pool','bar','kitchen','bar']})
    
    Out[4]: 
       id    place
    0   1      bar
    1   1     pool
    2   2      bar
    3   3  kitchen
    4   4      bar
    

    这里的网络结构是这样的 id 身份证件 如果他们去同一个地方。

    例如,这里 1 已连接到 2 4 bar .

    1. 3 未连接,因为 1. 去了 酒吧 pool kitchen (唯一的地方 3. 转到)

    我的真实数据是巨大的,大约50万。什么是获得 adjacency list source target target 就像在 https://networkx.github.io/documentation/networkx-1.10/reference/readwrite.adjlist.html

    adjacency_list
    1 2 4
    2 1 4
    4 1 2
    

    我们能避免循环和使用熊猫戏法吗?

    谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   BENY    7 年前

    使用 unique 然后将列0切换为1,将列1切换为0 concat 他们两个在一起

    adj=pd.DataFrame(df.groupby('place').id.unique().loc[lambda x : x.str.len()>1].tolist())
    pd.concat([adj,adj.rename(columns={0:1,1:0})])
    Out[810]: 
       0  1
    0  1  2
    0  2  1
    

    更新:

    newdf=df.merge(df,on='place')
    x=nx.from_pandas_dataframe(newdf,'id_x','id_y') # using merge to get the connect for all id by link columns place. 
    [list(itertools.permutations(x, len(x)) for x in list(nx.connected_components(x))] # using permutations get the all combination for each  connected_components in networkx 
    Out[821]: [[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]]
    

    数据输入

    df
    Out[822]: 
       id place
    0   1   bar
    1   1  pool
    2   2   bar
    3   3   bar
    
        2
  •  1
  •   Karn Kumar    7 年前

    >>> df
       id    place
    0   1      bar
    1   1     pool
    2   2      bar
    3   3  kitchen
    >>> df.groupby('place').id.nunique().value_counts()
    1    2
    2    1
    Name: id, dtype: int64