使用 networkx 检测社区

时间:2021-04-13 13:45:33

标签: python networkx

我有一个看起来像这样的数据库:

<头>
id_1 id_2 日期
H4FR923 AAE9987Y 01-01-2018

我是这样读取数据的:

    import pandas as pd 
    
    path = "data.csv"
    
    df = pd.read_csv(path) 

然后通过以下方式使用 netowkrx 创建网络:

    import networkx as nx 
    G = nx.from_pandas_edgelist(df, source='id_1', target='id_2', edge_attr='date')

现在我想检测社区,我需要根据日期定义社区。例如,就像我们在这个日期的日期列下: 1-1-2018 - 1-6-2018

我想建立一个社区来保存这个日期 1-1-2018 tp 1-6-2018 和 community_2 之间的所有节点,可能会有 2-6-2018 到 30-12-2018 这样的事情

所以每个社区都应该有具有一组日期的节点

有可能吗!!

这是我所做的:

from networkx.algorithms import community

partition = community.asyn_lpa_communities(G) 

def modularity(G, partition):
W = sum(G.edges[v, w].get('weight', 1) for v, w in G.edges)
summation = 0
for cluster_nodes in partition:
    s_c = sum(G.degree(n, weight='weight') for n in cluster_nodes)
    # Use subgraph to count only internal links
    C = G.subgraph(cluster_nodes)
    W_c = sum(C.edges[v, w].get('weight', 1) for v, w in C.edges)
    summation += W_c - s_c ** 2 / (4 * W)

return summation / W

但现在确定如何根据我上面描述的社区做任何帮助!!

1 个答案:

答案 0 :(得分:0)

我假设您想根据边数据帧中的 id_1date 节点进行分区。

根据您在评论中给出的规格,我相信您想要这样的东西:

import networkx as nx
import pandas as pd

data = {
    "id_1": [1, 2, 3],
    "id_2": [2, 3, 1],
    "date": ["date1", "date2", "date1"],
}


df = pd.DataFrame(data, columns=[x for x in data.keys()])

# df =
#    id_1  id_2   date
# 0     1     2  date1
# 1     2     3  date2
# 2     3     1  date1

node_attrs = dict(zip(df.id_1, df.date))

# node_attrs ={1: 'date1', 2: 'date2', 3: 'date1'}

for node in node_attrs:
    node_attrs[node] = {"date": node_attrs[node]}

for node in node_attrs:
    if node_attrs[node]["date"] == "date1":
        node_attrs[node]["partition"] = 1
    else:
        node_attrs[node]["partition"] = 2


# creating the graph
G = nx.from_pandas_edgelist(df, source="id_1", target="id_2")

nx.set_node_attributes(G, node_attrs)

print(G.nodes(data=True))

# output: [(1, {'date': 'date1', 'partition': 1}), (2, {'date': 'date2', 'partition': 2}), (3, {'date': 'date1', 'partition': 1})]

所有节点都根据其 date 属性进行分区。

相关问题