networkx.convert_matrix.from_pandas_edgelist¶
-
from_pandas_edgelist
(df, source='source', target='target', edge_attr=None, create_using=None)[source]¶ Return a graph from Pandas DataFrame containing an edge list.
The Pandas DataFrame should contain at least two columns of node names and zero or more columns of edge attributes. Each row will be processed as one edge instance.
Note: This function iterates over DataFrame.values, which is not guaranteed to retain the data type across columns in the row. This is only a problem if your row is entirely numeric and a mix of ints and floats. In that case, all values will be returned as floats. See the DataFrame.iterrows documentation for an example.
Parameters: - df (Pandas DataFrame) – An edge list representation of a graph
- source (str or int) – A valid column name (string or iteger) for the source nodes (for the directed case).
- target (str or int) – A valid column name (string or iteger) for the target nodes (for the directed case).
- edge_attr (str or int, iterable, True) – A valid column name (str or integer) or list of column names that will
be used to retrieve items from the row and add them to the graph as
edge attributes. If
True
, all of the remaining columns will be added. - create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to create. If graph instance, then cleared before populated.
See also
Examples
Simple integer weights on edges:
>>> import pandas as pd >>> pd.options.display.max_columns = 20 >>> import numpy as np >>> rng = np.random.RandomState(seed=5) >>> ints = rng.randint(1, 11, size=(3,2)) >>> a = ['A', 'B', 'C'] >>> b = ['D', 'A', 'E'] >>> df = pd.DataFrame(ints, columns=['weight', 'cost']) >>> df[0] = a >>> df['b'] = b >>> df[['weight', 'cost', 0, 'b']] weight cost 0 b 0 4 7 A D 1 7 1 B A 2 10 9 C E >>> G = nx.from_pandas_edgelist(df, 0, 'b', ['weight', 'cost']) >>> G['E']['C']['weight'] 10 >>> G['E']['C']['cost'] 9 >>> edges = pd.DataFrame({'source': [0, 1, 2], ... 'target': [2, 2, 3], ... 'weight': [3, 4, 5], ... 'color': ['red', 'blue', 'blue']}) >>> G = nx.from_pandas_edgelist(edges, edge_attr=True) >>> G[0][2]['color'] 'red'