Skip to content

Instantly share code, notes, and snippets.

@tomron
Created January 17, 2020 19:02
Show Gist options
  • Save tomron/1e9f8286be116f727cee450b06e05428 to your computer and use it in GitHub Desktop.
Save tomron/1e9f8286be116f727cee450b06e05428 to your computer and use it in GitHub Desktop.
import networkx as nx
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Multigraph example
G = nx.MultiGraph()
G.add_nodes_from([1, 2, 3])
G.add_edges_from([(1, 2), (1, 3), (1, 2)])
print(G.degree())
#[(1, 3), (2, 2), (3, 1)]
H = nx.Graph()
H.add_nodes_from([1, 2, 3])
H.add_edges_from([(1, 2), (1, 3), (1, 2)])
print(H.degree())
#[(1, 2), (2, 1), (3, 1)]
# Pandas example
df = pd.DataFrame([[1, 1, 4], [2, 1, 5], [3, 2, 6], [1, 1, 3]], columns=['source', 'destination', 'weight'])
print(df)
# source destination weight
# 0 1 1 4
# 1 2 1 5
# 2 3 2 6
# 3 1 1 3
G = nx.from_pandas_edgelist(df, 'source', 'destination', ['weight'], create_using=nx.MultiGraph)
print(nx.info(G))
# Name:
# Type: MultiGraph
# Number of nodes: 3
# Number of edges: 4
# Average degree: 2.6667
# Graph generators
# Complete graph
G = nx.complete_graph(n=9)
print(len(G.edges()), len(G.nodes()))
# 36 9
H = nx.complete_graph(n=9, create_using=nx.DiGraph)
print(len(H.edges()), len(H.nodes()))
# 72 9
J = nx.empty_graph(n=9)
print(len(J.edges()), len(J.nodes()))
# 0 9
K = nx.star_graph(n=9)
print(len(K.edges()), len(K.nodes()))
# 9 10
##
G1 = nx.binomial_graph(n=9, p=0.5, seed=1)
G2 = nx.binomial_graph(n=9, p=0.5, seed=1)
G3 = nx.binomial_graph(n=9, p=0.5)
print(G1.edges()==G2.edges(), G1.edges()==G3.edges())
# True False
G = nx.random_regular_graph(d=4, n=10)
nx.draw(G)
plt.show()
G = nx.random_tree(n=10)
nx.draw(G)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment