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

如何将Pandas DataFrame中的列表列拆分并合并为单列结构

拆分Pandas DataFrame中的列表列为单列结构

问题说明

原始DataFrame里,labels列是带方括号的字符串格式列表,Score列是原生列表,需要把这两列的列表元素拆分,转换成每行对应单个标签与分数的结构。

解决步骤

  1. 转换labels列格式:把字符串形式的列表转为真实列表,同时清理元素中的多余空格
  2. 拆分列表列:用explode方法将两列的列表元素分别展开为多行

完整代码示例

import pandas as pd

# 原始数据
data = {'labels': ['[management,workload,credibility]','[ethic,hardworking,profession]'],
        'Score': [[0.55,0.36,0.75],[0.41,0.23,0.14]]}
df = pd.DataFrame(data)

# 1. 将labels列的字符串转为列表
df['labels'] = df['labels'].str.strip('[]').str.split(',').apply(lambda x: [s.strip() for s in x])

# 2. 拆分两列列表,生成目标DataFrame
df_result = df.explode(['labels', 'Score'], ignore_index=True)

# 查看结果
print(df_result)

输出结果

labels  Score
0   management   0.55
1     workload   0.36
2  credibility   0.75
3        ethic   0.41
4   hardworking   0.23
5   profession   0.14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:21:06