Python: Snippet to convert csv into nodes-links json for D3.js network data

Network data format of D3.js  is commonly nodes-links json. The nodes contain id, ,name, and attributes. The links contain source, target, and value.
But making such json data by hand is tough since json requires many syntax words like {},[].
Unlike json, csv requires only “,” and you can make it by Excel. So I made the snippet to convert csv into the json format.

 

The nodes.csv and edges.csv responsible for nodes and links respectively. The tables in Excel look like below.

nodes.csv:

id name Group
0 Kent Senior
1 Vitor Middle
2 Marius Junior
3 Mike Junior
4 Steve Senior

edges.csv:

source target value
0 1 3
0 2 4
0 4 4
1 3 1
2 0 5
2 3 5
2 4 1
3 2 3
3 4 4
4 0 4
4 3 5

 

The importing snippet is below.
The python snippet needs NetworkX ,Pandas, and matplotlib. % is for ipython notebook. I used Pandas only for read csv; matplotlib only for check imported data visually.

import networkx as nx
import pandas as pd
from matplotlib.pylab import plt
%matplotlib inline

G = nx.Graph()

# Read csv for nodes and edges using pandas:
nodes = pd.read_csv("nodes.csv")
edges = pd.read_csv("edges.csv")

# Dataframe to list:
nodes_list = nodes.values.tolist()
edges_list = edges.values.tolist()

# Import id, name, and group into node of Networkx:
for i in nodes_list:
    G.add_node(i[0], name=i[1], group=i[2])

# Import source, target, and value into edges of Networkx:
for i in edges_list:
    G.add_edge(i[0],i[1], value=i[2])

# Visualize the network:
nx.draw_networkx(G)

data_networkx_csv2_value1_viz1

 

The below writes json for nodes-links format.

# Write json for nodes-links format:
import json
j = json_graph.node_link_data(G)

js = json.dumps(j, ensure_ascii=False, indent=2)
with open("node-link-value.json", "w") as file:
     file.write(js)

The generated node-link-value.json is this:

{
  "multigraph": false,
  "graph": [],
  "nodes": [
    {
      "id": 0,
      "group": "Senior",
      "name": "Kent"
    },
    {
      "id": 1,
      "group": "Middle",
      "name": "Vitor"
    },
    {
      "id": 2,
      "group": "Junior",
      "name": "Marius"
    },
    {
      "id": 3,
      "group": "Junior",
      "name": "Mike"
    },
    {
      "id": 4,
      "group": "Senior",
      "name": "Steve"
    }
  ],
  "links": [
    {
      "source": 0,
      "value": 3,
      "target": 1
    },
    {
      "source": 0,
      "value": 5,
      "target": 2
    },
    {
      "source": 0,
      "value": 4,
      "target": 4
    },
    {
      "source": 1,
      "value": 1,
      "target": 3
    },
    {
      "source": 2,
      "value": 3,
      "target": 3
    },
    {
      "source": 2,
      "value": 1,
      "target": 4
    },
    {
      "source": 3,
      "value": 5,
      "target": 4
    }
  ],
  "directed": false
}
2 Comments

Leave a Reply