【问题标题】:Create Pandas dataframe from JSON build based on nested lists基于嵌套列表从 JSON 构建创建 Pandas 数据框
【发布时间】:2021-04-20 22:50:07
【问题描述】:

我想使用以下嵌套列表:

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

结构=[['jumps', [['fox', [['The'], ['quick'], ['brown']]], ['over', [['dog', [ ['the'], ['lazy']]]]]]]]

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

          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 都没有成功。

感谢任何见解。

【问题讨论】:

  • 您需要保留顺序还是可以按任何顺序排列?
  • 任何顺序,只要保持关系即可。

标签: python json pandas nested networkx


【解决方案1】:

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

让我们使用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
}

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

【讨论】:

    【解决方案2】:

    这是一个树状结构,这让我觉得这里应该使用递归函数。我会这样做:

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

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

    输出:

        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
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2022-08-03
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2022-06-13
      • 2020-01-21
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多