python - 如何将嵌套列表转换为数据框?
问题描述
我有一长串在 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
等等等等
解决方案
假设您可以将项目符号转换为 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
推荐阅读
- javascript - 使用 javascript 使用基于 json 的烧瓶 api 的现代方法
- reactjs - 在 Prime React 中上传文件时避免使用 URL 属性的查询
- sql - 列出PostgreSQL中物化视图使用的表?
- playframework - 旧 Spring Zuul 路由与 Play Framework 应用程序一起使用的迁移路径
- events - Solidity 事件 n 发出语法
- lambda - 简单无服务器部署上的“s3:CreateBucket Access Denied”
- c - select() 调用卡住了
- javascript - 为什么获取div背景不返回背景
- python - 如何使用python计算csv文件的分组项目上特定项目的出现
- vb.net - vb.net 无法使用 ms.access 数据库保存图片