基于嵌套列表从 JSON 构建创建 Pandas 数据框

时间:2021-01-15 21:54:07

标签: python json pandas nested networkx

我想使用以下嵌套列表:

  • 首先:创建一个字典
  • 第二:从字典中,创建一个 Pandas 数据框

structure=[['jumps', [['fox', [['The'], ['quick'], ['brown']]], ['over', [['dog', [ ['the'], ['懒惰']]]]]]]]

这个嵌套列表来自具有依赖关系的解析树结构:

          jumps              
       _____|________         
      |             over     
      |              |        
     fox            dog      
  ____|_____      ___|____    
The quick brown the      lazy

我的想法是在一个 JSON 文件中转换这个嵌套列表,然后创建一个如下所示的 Pandas 数据框:

jumps fox
jumps over
fox The
fox quick
fox brown
over dog
dog the
dog lazy

以便可以使用 networkx 绘制此数据框。

到目前为止,我尝试了 json.dumpsdict,但没有成功。

感谢任何见解。

2 个答案:

答案 0 :(得分:3)

这是一个树状结构,这让我觉得这里应该使用递归函数。这是我将如何做到的:

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'])

它是如何工作的:它遍历每个列表,记住它看到的最后一个项目是什么。对于它找到的每个列表,它用该列表调用自己。这个函数的输出是一个生成器,它为图中的每个“边”生成一个元组。这可以导入到熊猫数据框中。

输出:

    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

答案 1 :(得分:1)

我错误地阅读了问题,并假设您想绘制图形,而不是转换嵌套列表。 @Nick 的解决方案是最好的方法。 仅将此答案视为附加信息而非解决方案

让我们使用 graphviz 并为 Digraph 创建我们自己的 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
}

enter image description here

您可以在他们的可视化编辑器中使用 graphviz here。另请阅读 documentation 以了解有关这些图形元素和更复杂图形的自定义选项。