首页 > 解决方案 > 如何将嵌套列表转换为数据框?

问题描述

我有一长串在 word doc 中标明的部分。我需要把它变成一个数据表。

示例输入列表:

= Fasteners

    o Screws

        - Machine

            +Round Head

            +Pan Head

            +Flat Head

       - Tapping

            +Type AB

            +Type A

示例输出表:感谢查看!

Parent   |Child |Type   |Style                               
Fasteners|Screws|Machine|Round Head    
Fasteners|Screws|Machine|Pan Head    
Fasteners|Screws|Machine|Flat Head    
Fasteners|Screws|Tapping|Type AB    
Fasteners|Screws|Tapping|Type A

等等等等

标签: pythonrexcel

解决方案


假设您可以将项目符号转换为 Python 字典(因为如果它是嵌套的,这可能是存储所有内容的最佳方式):

import pandas as pd

parts = {  
     'Fasteners':{  
        'Screws':{  
           'Machine':['Round Head','Pan Head','Flat Head'],
           'Tapping':['Type AB','Type A']
        }
     }
}

df_dict = {'Parent': [], 'Child': [], 'Type': [], 'Style': []}
for parent, v1 in parts.items():
    for child, v2 in v1.items():
        for child_type, v3 in v2.items():
            for style in v3:
                df_dict['Parent'].append(parent)
                df_dict['Child'].append(child)
                df_dict['Type'].append(child_type) # Not named type because type is a native Python function
                df_dict['Style'].append(style)

df = pd.DataFrame(df_dict)
print(df)

如果您有一个字典,其中每个键是列,每个值是值列表(彼此按顺序),Pandas 在创建数据框时效果最好。我在这里所做的是遍历嵌套字典中的每个键和值,以便我可以生成列表,并在必要时重复(以易于理解的方式)。为字典创建一个迭代器parts.items(),它将遍历每个键及其对应的值。这是输出:

      Parent   Child     Type       Style
0  Fasteners  Screws  Machine  Round Head
1  Fasteners  Screws  Machine    Pan Head
2  Fasteners  Screws  Machine   Flat Head
3  Fasteners  Screws  Tapping     Type AB
4  Fasteners  Screws  Tapping      Type A

推荐阅读