簡體   English   中英

Create Pandas dataframe from JSON 基於嵌套列表構建

[英]Create Pandas dataframe from JSON build based on nested lists

我想使用以下嵌套列表來:

  • 第一:創建字典
  • 第二:從字典中,創建一個 Pandas dataframe

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.dumpsdict沒有成功。

任何見解表示贊賞。

這是一個樹狀結構,這讓我覺得這里應該使用遞歸的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
}

在此處輸入圖像描述

您可以他們的可視化編輯器上使用graphviz 另請閱讀有關這些圖形元素和更復雜圖形的自定義選項的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM