我有一个工作正常的python脚本,该脚本会提取csv列数据并将其转换为json文件,以供d3 sunburst可视化读取。问题在于,在最终子元素上没有“ size”元素可以正确填充朝阳图。
下面是我拥有的脚本,该脚本可以按需要将cv读取到json。我尝试使用if else循环修改脚本,以找到没有子元素(最后一个元素)的位置,然后在该元素上附加“ size:1”,但是什么也没发生。
这是示例csv数据。该代码应该对任何东西都有效。
能量,修饰,脱落,可训练性,成群,繁殖
定期运动,每周2-3次刷牙,季节性,简单训练,玩具组,Affenpinscher
ui
最终的子元素需要读取如下内容:
import csv
from collections import defaultdict
def ctree():
return defaultdict(ctree)
def build_leaf(name, leaf):
res = {"name": name}
# add children node if the leaf actually has any children
if len(leaf.keys()) > 0:
res["children"] = [build_leaf(k, v) for k, v in leaf.items()]
return res
def main():
tree = ctree()
# NOTE: you need to have test.csv file as neighbor to this file
with open('test.csv') as csvfile:
reader = csv.reader(csvfile)
for rid, row in enumerate(reader):
if rid == 0:
continue
# usage of python magic to construct dynamic tree structure and
# basically grouping csv values under their parents
leaf = tree[row[0]]
for cid in range(1, len(row)):
leaf = leaf[row[cid]]
# building a custom tree structure
res = []
for name, leaf in tree.items():
res.append(build_leaf(name, leaf))
# this is what I tried to append the size element
def parseTree(leaf):
if len(leaf["children"]) == 0:
return obj["size"] == 1
else:
for child in leaf["children"]:
leaf['children'].append(parseTree(child))
# printing results into the terminal
import json
import uuid
from IPython.display import display_javascript, display_html, display
print(json.dumps(res, indent=2))
main()
答案 0 :(得分:0)
要将size
添加到最后一个条目:
import csv
from collections import defaultdict
import json
#import uuid
#from IPython.display import display_javascript, display_html, display
def ctree():
return defaultdict(ctree)
def build_leaf(name, leaf):
res = {"name": name}
# add children node if the leaf actually has any children
if leaf.keys():
res["children"] = [build_leaf(k, v) for k, v in leaf.items()]
else:
res['size'] = 1
return res
def main():
tree = ctree()
# NOTE: you need to have test.csv file as neighbor to this file
with open('test.csv') as csvfile:
reader = csv.reader(csvfile)
header = next(reader) # read the header row
for row in reader:
# usage of python magic to construct dynamic tree structure and
# basically grouping csv values under their parents
leaf = tree[row[0]]
for value in row[1:]:
leaf = leaf[value]
# building a custom tree structure
res = []
for name, leaf in tree.items():
res.append(build_leaf(name, leaf))
# printing results into the terminal
print(json.dumps(res, indent=2))
main()