将电子表格转换为 D3 的嵌套字典形式
Convert spreadsheet to nested dictionary form for D3
这个有问题。感觉好像我已经完成了类似的数据转换,但是这个让我陷入了 loop.
希望将电子表格数据转换为将用于 D3 可视化的嵌套 JSON,将其称为“flare.json”。
目标 JSON 看起来像这样(显然,字典也一样好):
{
"name": "root",
"children": [
{
"name": "A1",
"children": [
{
"name": "A2",
"children": [
{
"name": "A3",
"children": [
{
"name": "A4",
"children": [
]
}
]
}
]
}
]
},
{
"name": "B1",
"children": [
{
"name": "B2",
"children": [
{
"name": "B3",
"children": [
{
"name": "B4",
"children": [
]
}
]
}
]
}
]
}
]
}
我正在使用 openpyxl 从电子表格中提取数据,该电子表格提供了一个包含每个列值的元组的根元组。
例如
(
('A1','A2','A3','A4'),
('B1','B2','B3','B4'),
)
我知道有 101 种不同的方法可以做到这一点,考虑使用来自 pandas 的数据帧,我确信 openpyxl 有无数种这种东西的方法和转换。但无论出于何种原因,今天都很难想象这个过程。提前致谢。
应该这样做:
def convert_data(data):
out = {'name': 'root', 'children': []}
for row in data:
out['children'].append({})
current = out['children']
for value in row:
current[-1]['name'] = value
current[-1]['children'] = [{}]
current = current[-1]['children']
return out
data = (('A1','A2','A3','A4'), ('B1','B2','B3','B4'))
new_structure = convert_data(data)
您显然可以使用 json.dumps
之类的东西将其输出为 JSON 字符串。
这个有问题。感觉好像我已经完成了类似的数据转换,但是这个让我陷入了 loop.
希望将电子表格数据转换为将用于 D3 可视化的嵌套 JSON,将其称为“flare.json”。
目标 JSON 看起来像这样(显然,字典也一样好):
{
"name": "root",
"children": [
{
"name": "A1",
"children": [
{
"name": "A2",
"children": [
{
"name": "A3",
"children": [
{
"name": "A4",
"children": [
]
}
]
}
]
}
]
},
{
"name": "B1",
"children": [
{
"name": "B2",
"children": [
{
"name": "B3",
"children": [
{
"name": "B4",
"children": [
]
}
]
}
]
}
]
}
]
}
我正在使用 openpyxl 从电子表格中提取数据,该电子表格提供了一个包含每个列值的元组的根元组。
例如
(
('A1','A2','A3','A4'),
('B1','B2','B3','B4'),
)
我知道有 101 种不同的方法可以做到这一点,考虑使用来自 pandas 的数据帧,我确信 openpyxl 有无数种这种东西的方法和转换。但无论出于何种原因,今天都很难想象这个过程。提前致谢。
应该这样做:
def convert_data(data):
out = {'name': 'root', 'children': []}
for row in data:
out['children'].append({})
current = out['children']
for value in row:
current[-1]['name'] = value
current[-1]['children'] = [{}]
current = current[-1]['children']
return out
data = (('A1','A2','A3','A4'), ('B1','B2','B3','B4'))
new_structure = convert_data(data)
您显然可以使用 json.dumps
之类的东西将其输出为 JSON 字符串。