You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将值含嵌套列表的字典转换为Pandas DataFrame?

解决嵌套字典转DataFrame的格式问题

原字典的test值为嵌套列表,直接使用pd.DataFrame.from_dict([sample_dict])会将整个列表作为单个单元格的值,无法拆分出所需字段。以下是两种可行的解决思路:

思路1:提前重构字典结构

将嵌套列表拆分为独立键值,让DataFrame直接识别各字段:

import pandas as pd

sample_dict = {'test':['test string',['feature1','feature2', 'feature3']]}
# 重构字典,拆分出文本和特征列表两个字段
formatted_data = {
    'test_str': sample_dict['test'][0],
    'features': sample_dict['test'][1]
}

# 转换为DataFrame
df = pd.DataFrame([formatted_data])
print(df)

输出结果:

test_str                     features
0  test string  [feature1, feature2, feature3]

如果需要将特征列表展开为多行(每个特征对应一行文本),使用explode方法:

df_exploded = df.explode('features').reset_index(drop=True)
print(df_exploded)

输出结果:

test_str   features
0  test string  feature1
1  test string  feature2
2  test string  feature3

思路2:转换后拆分列

如果无法修改原始字典,先转换为DataFrame,再拆分嵌套列表:

import pandas as pd

sample_dict = {'test':['test string',['feature1','feature2', 'feature3']]}
df = pd.DataFrame.from_dict([sample_dict])

# 将'test'列的嵌套列表拆分为两列
df[['test_str', 'features']] = pd.DataFrame(df['test'].tolist(), index=df.index)

# 删除原'test'列
df = df.drop('test', axis=1)
print(df)

后续同样可以用explode方法展开特征列表为多行,效果同思路1。

内容的提问来源于stack exchange,提问作者mikelowry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:05:28