附加“大小";森伯斯特图的最后一个json子元素的元素 [英] Appending "size" element to last json child element for a sunburst diagram

查看:81
本文介绍了附加“大小";森伯斯特图的最后一个json子元素的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作正常的python脚本,该脚本会提取csv列数据并将其转换为json文件,以供d3 sunburst可视化读取.问题在于,在最终子元素上没有"size"元素可以正确填充朝阳图.

I have a working python script that takes my csv columns data and converts it to a json file to be read by my d3 sunburst visualization. Problem is that there is no "size" element at the final child element which is needed to populate the sunburst diagram correctly.

下面是我拥有的脚本,该脚本可以按需要将cv读取到json.我尝试使用if else循环修改脚本,以查找没有子元素(最后一个元素)的位置,然后在该元素上附加"size:1",但是什么也没发生.

Below is the script I have that reads the csv to a json the way I need it. I've tried modifying the script with an if else loop to find where there is no child element (the last element) and then appending on that element the "size: 1" but nothing happens.

这是示例csv数据.该代码应该对任何东西都有效.

This is example csv data. The code should work for anything though.

能量,修饰,脱落,可训练性,成群,繁殖

Energy, Grooming, Shedding, Trainability, Group, Breed

定期运动,每周2-3次刷牙,季节性,简单训练,玩具组,Affenpinscher

Regular Exercise, 2-3 Times a Week Brushing, Seasonal, Easy Training, Toy Group, Affenpinscher

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()

最终的子元素需要读取如下内容:

The final child element needs to read something like this:

[
{
    "name": "Regular Exercise",
    "children": [
        {
            "name": "2-3 Times a Week Brushing",
            "children": [
                {
                    "name": "Seasonal",
                    "children": [
                        {
                            "name": "Easy Training",
                            "children": [
                                {
                                    "name": "Toy Group",
                                    "children": [
                                        {
                                            "name": "Affenpinscher",
                                            "size": 1
                                        }
                                    ]
                                }]}]}]}]}]}

推荐答案

要将size添加到最后一个条目:

To add size to the last entry:

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()

这篇关于附加“大小";森伯斯特图的最后一个json子元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆