使用 pandas 数据框将边权重分配给 networkx 图
Assign edge weights to a networkx graph using pandas dataframe
我正在 python 3 中构建一个 networkx 图。我正在使用 pandas 数据框为该图提供边和节点。这是我所做的:
test = pd.read_csv("/home/Desktop/test_call1", delimiter = ';')
g_test = nx.from_pandas_edgelist(test, 'number', 'contactNumber', edge_attr='callDuration')
我想要的是 pandas 数据框的 "callDuration" 列充当 networkx 图的边的权重,边的粗细也相应变化。
我还想获得 'n' 最大加权边。
让我们试试:
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
df = pd.DataFrame({'number':['123','234','345'],'contactnumber':['234','345','123'],'callduration':[1,2,4]})
df
G = nx.from_pandas_edgelist(df,'number','contactnumber', edge_attr='callduration')
durations = [i['callduration'] for i in dict(G.edges).values()]
labels = [i for i in dict(G.nodes).keys()]
labels = {i:i for i in dict(G.nodes).keys()}
fig, ax = plt.subplots(figsize=(12,5))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, ax = ax, labels=True)
nx.draw_networkx_edges(G, pos, width=durations, ax=ax)
_ = nx.draw_networkx_labels(G, pos, labels, ax=ax)
输出:
不同意所说的内容。在考虑每个边的权重(如 pagerank 或中间中心性)的不同指标的计算中,如果存储为边属性,则您的权重将不会被考虑在内。
使用图表。
Add_edges(source, target, weight, *attrs)
我正在 python 3 中构建一个 networkx 图。我正在使用 pandas 数据框为该图提供边和节点。这是我所做的:
test = pd.read_csv("/home/Desktop/test_call1", delimiter = ';')
g_test = nx.from_pandas_edgelist(test, 'number', 'contactNumber', edge_attr='callDuration')
我想要的是 pandas 数据框的 "callDuration" 列充当 networkx 图的边的权重,边的粗细也相应变化。
我还想获得 'n' 最大加权边。
让我们试试:
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
df = pd.DataFrame({'number':['123','234','345'],'contactnumber':['234','345','123'],'callduration':[1,2,4]})
df
G = nx.from_pandas_edgelist(df,'number','contactnumber', edge_attr='callduration')
durations = [i['callduration'] for i in dict(G.edges).values()]
labels = [i for i in dict(G.nodes).keys()]
labels = {i:i for i in dict(G.nodes).keys()}
fig, ax = plt.subplots(figsize=(12,5))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, ax = ax, labels=True)
nx.draw_networkx_edges(G, pos, width=durations, ax=ax)
_ = nx.draw_networkx_labels(G, pos, labels, ax=ax)
输出:
不同意所说的内容。在考虑每个边的权重(如 pagerank 或中间中心性)的不同指标的计算中,如果存储为边属性,则您的权重将不会被考虑在内。 使用图表。
Add_edges(source, target, weight, *attrs)