如何将DataFrame中每行的列表提取为独立DataFrame?
按ID拆分含列表列的DataFrame为独立DataFrame
原始DataFrame结构
| ID | fields |
|---|---|
| 1 | [egg, apple, toy..] |
| 2 | [orange, bear, red..] |
目标格式(以ID=1为例)
| Value |
|---|
| egg |
| apple |
| toy |
实现方法
方法1:遍历生成并存储到字典
这种方式直观易懂,同时用字典统一管理所有独立DataFrame,避免零散变量混乱:
import pandas as pd # 构造示例数据(替换成你的真实DataFrame) df = pd.DataFrame({ 'ID': [1, 2], 'fields': [['egg', 'apple', 'toy'], ['orange', 'bear', 'red']] }) # 初始化字典存储每个ID对应的DataFrame id_dataframes = {} # 遍历每一行生成独立DataFrame for _, row in df.iterrows(): # 将列表转为指定列名的DataFrame single_df = pd.DataFrame(row['fields'], columns=['Value']) # 用ID作为键存入字典 id_dataframes[row['ID']] = single_df # 调用示例:获取ID=1的DataFrame print(id_dataframes[1])
方法2:用索引映射+字典推导式(更简洁高效)
如果你的DataFrame中每个ID唯一,这种写法更紧凑:
import pandas as pd df = pd.DataFrame({ 'ID': [1, 2], 'fields': [['egg', 'apple', 'toy'], ['orange', 'bear', 'red']] }) # 直接通过索引映射生成字典 id_dataframes = { id_val: pd.DataFrame(fields, columns=['Value']) for id_val, fields in df.set_index('ID')['fields'].items() } # 调用示例:查看ID=2的DataFrame print(id_dataframes[2])
内容的提问来源于stack exchange,提问作者siusiusiu
相关产品推荐
相关产品推荐

