-
Notifications
You must be signed in to change notification settings - Fork 2
/
df2json.py
97 lines (73 loc) · 2.73 KB
/
df2json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
class to create json files with
parent/child hierarchy from a pandas
DataFrame
example use of the json file would
be in a sunburst plot
"""
import os, sys
import pandas as pd
import json
class jsonMaker(object):
def __init__(self, sql='', df='', jsonfile=''):
self.conn = ''
self.servername = ''
self.dbname = ''
self.sql = sql
self.df = df
self.jsonfile = jsonfile
def sqlconn(self):
"""
example method to connect to a SQL server
uses pandas to read the return query directly
into a DataFrame
"""
import pyodbc
conn = pyodbc.connect("DRIVER=SQL Server; \
SERVER={0}; \
database={1}; \
Trusted_Connection=yes" \
.format(self.servername,
self.dbname))
self.conn = conn
self.df = pd.read_sql(self.sql, conn)
def writeJSON(self, df=None, jsonfile=None):
"""
writeJSON - used to create a json file from a pandas dataframe
for use in a sunburst plot.
Parameters
-----------------
df: pandas dataframe, can contain multiple columns, beginning
with most generic classification first, down to most specific
classification (e.g. state, office, section, employee) - last
column should be numerical value used to calculate proportion
for each class
jsonfile: string, name of json output file
Modified from:
http://stackoverflow.com/questions/19317115/convert-flat-json-file-to-hierarchical-json-data-like-flare-json-d3-example-fil?rq=1
"""
if not isinstance(df, pd.DataFrame):
df = self.df
if jsonfile == None:
jsonfile = self.jsonfile
dataStructure = {'name':'', 'children': []}
for data in df.iterrows():
current = dataStructure
depthCursor = current['children']
for i, item in enumerate(data[1][:-2]):
idx = None
j = None
for j, c in enumerate(depthCursor):
if item in c.values():
idx = j
if idx == None:
depthCursor.append({'name':item, 'children':[]})
idx = len(depthCursor) - 1
depthCursor = depthCursor[idx]['children']
if i == len(data[1])-3:
depthCursor.append({'name':'{}'.format(data[1][-2]),
'size': data[1][-1]})
current = depthCursor
f = open(jsonfile, 'w')
json.dump(dataStructure, f, indent=4)
f.close()