[英]Create Pandas dataframe from JSON build based on nested lists
我想使用以下嵌套列表来:
structure=[['jumps', [['fox', [['The'], ['quick'], ['brown']]], ['over', [['dog', [['the '], ['懒惰的']]]]]]]]
此嵌套列表来自具有依赖关系的已解析树结构:
jumps
_____|________
| over
| |
fox dog
____|_____ ___|____
The quick brown the lazy
我的想法是将这个嵌套列表转换为 JSON 文件,然后创建一个 Pandas dataframe 如下所示:
jumps fox
jumps over
fox The
fox quick
fox brown
over dog
dog the
dog lazy
这样这个 dataframe 可以用networkx
绘制。
到目前为止,我尝试使用json.dumps
和dict
没有成功。
任何见解表示赞赏。
这是一个树状结构,这让我觉得这里应该使用递归的function。 我会这样做:
import pandas as pd
def recurse(l, parent=None):
assert isinstance(l, list)
for item in l:
if isinstance(item, str):
if parent is not None:
yield (parent, item)
parent = item
elif isinstance(item, list):
yield from recurse(item, parent)
else:
raise Exception(f"Unknown type {type(item)}")
structure=[['jumps', [['fox', [['The'], ['quick'], ['brown']]], ['over', [['dog', [['the'], ['lazy']]]]]]]]
df = pd.DataFrame(recurse(structure), columns=['from', 'to'])
它是如何工作的:它遍历每个列表,记住它看到的最后一个项目是什么。 对于它找到的每个列表,它都会用该列表调用自己。 这个 function 的 output 是一个生成器,它为图中的每个“边”生成一个元组。 这个可以导入一个pandas dataframe。
Output:
from to
0 jumps fox
1 fox The
2 fox quick
3 fox brown
4 jumps over
5 over dog
6 dog the
7 dog lazy
我错误地阅读了这个问题并假设你想要 plot 图表,而不是转换嵌套列表。 @Nick 的解决方案是 go 的最佳方式。将此答案仅视为附加信息而不是解决方案
让我们使用graphviz
并为有向图创建我们自己的 DOT -
from graphviz import Source
l = [('jumps','fox'),
('jumps', 'over'),
('fox', 'The'),
('fox', 'quick'),
('fox', 'brown'),
('over', 'dog'),
('dog', 'the'),
('dog', 'lazy')]
dotgraph = 'digraph G {' + ' '.join([i+'->'+j for i,j in l]) + '}'
print(dotgraph)
s = Source(dotgraph, filename="test1.gv", format="png")
s.view()
digraph G {
jumps->fox
jumps->over
fox->The
fox->quick
fox->brown
over->dog
dog->the
dog->lazy
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.