Convert#
Turn a NumPy or SciPy sparse adjacency matrix, or a pandas edge-list
DataFrame, into a NetworkX graph. The dispatch wrappers
backbone(),
backbone_from_weighted() and
backbone_from_unweighted() accept these inputs
directly. To go back to a DataFrame, use
to_pandas_edgelist().
Bipartite incidence matrices are accepted by the
bipartite functions themselves.
Conversion from NumPy, SciPy sparse and pandas data to NetworkX graphs.
Backbone methods score the edges of a NetworkX graph and return a graph. Data
held as a weighted adjacency matrix or as an edge-list DataFrame can be
turned into a graph with to_graph(), which wraps
NetworkX’s own converters
(from_numpy_array(),
from_scipy_sparse_array() and
from_pandas_edgelist()) and adds the checks a
backbone needs: an undirected graph must come from a symmetric matrix, and an
edge list must not list the same node pair twice. The dispatch wrappers
backbone(),
backbone_from_weighted() and
backbone_from_unweighted() call it for you. The
individual scorers keep graph-only signatures, as NetworkX functions do:
convert once with to_graph() and pass the graph to
as many scorers as you like.
For the way back, to_pandas_edgelist() returns
a backbone, or a scored graph, as a tidy DataFrame with source and
target columns and one column per edge attribute (weights and scores):
>>> import networkx as nx
>>> import nx_backbone as nb
>>> H = nb.disparity_filter(nx.les_miserables_graph())
>>> df = nx.to_pandas_edgelist(H)
>>> list(df.columns)
['source', 'target', 'weight', 'disparity_pvalue']
NumPy, SciPy and pandas are optional: they are only needed for the matching
input type and are never imported by to_graph() for
graph input.
- nx_backbone.to_graph(data, *, nodelist=None, directed=False, source='source', target='target', weight='weight')[source]#
Return a NetworkX graph for a graph, adjacency matrix or edge list.
Uses NetworkX’s own converters:
from_numpy_array()for a NumPy array,from_scipy_sparse_array()for a SciPy sparse array or matrix, andfrom_pandas_edgelist()for a pandasDataFrame. Unlike those converters, it refuses input that would silently lose edges: an asymmetric matrix for an undirected graph, or an edge list that lists a node pair more than once.- Parameters:
- datagraph, array-like, sparse array or DataFrame
A NetworkX graph (returned unchanged, and the other arguments are ignored); a square adjacency matrix (NumPy array or array-like, or SciPy sparse array or matrix) whose nonzero entry
A[i, j]is an edge of weightA[i, j]; or a pandas edge-listDataFramewith one row per edge.- nodelistsequence or None, optional (default=None)
Node labels for the rows and columns of an adjacency matrix (default
0, 1, ..., n - 1). Isolated nodes are kept.- directedbool, optional (default=False)
Build a
DiGraph, withA[i, j](or a row) the edge fromi(source) toj(target). IfFalseaGraphis built and an adjacency matrix must be symmetric.- source, targetstr, optional (default=”source”, “target”)
Edge-list columns holding the two endpoints of each edge.
- weightstr or None, optional (default=”weight”)
Edge attribute that stores the matrix entries, and edge-list column copied to that attribute (when present). If
Noneno edge attributes are stored.
- Returns:
- Raises:
- TypeError
If data is not a graph, an array, a sparse array or a
DataFrame.- ValueError
If an adjacency matrix is not square, not real-valued, or (with
directed=False) not symmetric; if nodelist does not match it; or if an edge list lacks the source / target columns or has duplicate node pairs.
Examples
A symmetric NumPy adjacency matrix with node labels:
>>> import numpy as np >>> import nx_backbone as nb >>> A = np.array([[0, 3, 1], [3, 0, 2], [1, 2, 0]]) >>> G = nb.to_graph(A, nodelist=["a", "b", "c"]) >>> sorted(G.edges(data="weight")) [('a', 'b', 3), ('a', 'c', 1), ('b', 'c', 2)]
The same network as a pandas edge list with custom column names (pandas is optional, so this example is not run in the test suite):
>>> import pandas as pd >>> df = pd.DataFrame( ... {"from": ["a", "a", "b"], "to": ["b", "c", "c"], "w": [3, 1, 2]} ... ) >>> G = nb.to_graph(df, source="from", target="to", weight="w") >>> sorted(G.edges(data="w")) [('a', 'b', 3), ('a', 'c', 1), ('b', 'c', 2)]
A SciPy sparse adjacency matrix gives the same backbone as the graph it came from:
>>> import networkx as nx >>> G = nx.les_miserables_graph() >>> nodes = list(G) >>> A = nx.to_scipy_sparse_array(G, nodelist=nodes) >>> H = nb.disparity_filter(nb.to_graph(A, nodelist=nodes)) >>> dict(H.edges) == dict(nb.disparity_filter(G).edges) True
Computational complexity estimate is
O(n + m)time andO(n + m)space.