【问题标题】:igraph Graph from numpy or pandas adjacency matrixigraph 来自 numpy 或 pandas 邻接矩阵的图
【发布时间】:2015-06-21 16:51:14
【问题描述】:

我有一个存储为pandas.DataFrame 的邻接矩阵:

node_names = ['A', 'B', 'C']
a = pd.DataFrame([[1,2,3],[3,1,1],[4,0,2]],
    index=node_names, columns=node_names)
a_numpy = a.as_matrix()

我想从pandasnumpy 邻接矩阵创建一个igraph.Graph。在理想世界中,节点将按预期命名。

这可能吗? The tutorial 似乎对这个问题保持沉默。

【问题讨论】:

  • 严格来说,adjacency matrices 是布尔值。 a_numpy 中的值实际上是什么意思?它们是连接权重吗?
  • @ali_m 我的意思是指边权重。

标签: python numpy pandas igraph


【解决方案1】:

在 igraph 中,您可以使用 igraph.Graph.Adjacency 从邻接矩阵创建图形,而无需使用 zip。当使用加权邻接矩阵并将其存储在np.arraypd.DataFrame 中时,需要注意一些事项。

  • igraph.Graph.Adjacency 不能将np.array 作为参数,但使用tolist 很容易解决。

  • 邻接矩阵中的整数被解释为节点之间的边数而不是权重,通过使用邻接作为布尔值来解决。

如何做的一个例子:

import igraph
import pandas as pd

node_names = ['A', 'B', 'C']
a = pd.DataFrame([[1,2,3],[3,1,1],[4,0,2]], index=node_names, columns=node_names)

# Get the values as np.array, it's more convenenient.
A = a.values

# Create graph, A.astype(bool).tolist() or (A / A).tolist() can also be used.
g = igraph.Graph.Adjacency((A > 0).tolist())

# Add edge weights and node labels.
g.es['weight'] = A[A.nonzero()]
g.vs['label'] = node_names  # or a.index/a.columns

您可以通过以下方式使用get_adjacency 重构您的邻接数据框:

df_from_g = pd.DataFrame(g.get_adjacency(attribute='weight').data,
                         columns=g.vs['label'], index=g.vs['label'])
(df_from_g == a).all().all()  # --> True

【讨论】:

  • 完美! +1 因为Adjacency 将数字解释为链接数,而不是链接权重。
  • 如果行是“从”节点,列是“到”节点,您将如何将此图转换为有向图。
  • a.to_numpy() is preferred to a.values
【解决方案2】:

严格来说,adjacency matrix 是布尔值,1 表示存在连接,0 表示不存在。由于a_numpy 矩阵中的许多值都大于 1,因此我假设它们对应于图中的边权重。

import igraph

# get the row, col indices of the non-zero elements in your adjacency matrix
conn_indices = np.where(a_numpy)

# get the weights corresponding to these indices
weights = a_numpy[conn_indices]

# a sequence of (i, j) tuples, each corresponding to an edge from i -> j
edges = zip(*conn_indices)

# initialize the graph from the edge sequence
G = igraph.Graph(edges=edges, directed=True)

# assign node names and weights to be attributes of the vertices and edges
# respectively
G.vs['label'] = node_names
G.es['weight'] = weights

# I will also assign the weights to the 'width' attribute of the edges. this
# means that igraph.plot will set the line thicknesses according to the edge
# weights
G.es['width'] = weights

# plot the graph, just for fun
igraph.plot(G, layout="rt", labels=True, margin=80)

【讨论】:

    【解决方案3】:

    This is possibleigraph.Graph.Weighted_Adjacency

    g = igraph.Graph.Weighted_Adjacency(a.to_numpy().tolist())
    

    pandas.DataFrame.as_matrixhas been deprecated, 所以应该改用pandas.DataFrame.to_numpy。 此外,a.to_numpy() 给出的 numpy.ndarray 必须先转换为带有tolist() 的列表,然后才能传递给Weighted_Adjacency

    节点名称可以存储为另一个属性

    g.vs['name'] = node_names
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多