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

如何将Pandas中含3个数值的object类型列拆分为三列?

解决方案

方法一:字符串清洗后拆分

先将scores列的字符串格式转换为数值列表,再拆分到目标列:

# 清理字符串并转换为float列表
df['scores'] = df['scores'].str.replace(r'[\[\]]', '', regex=True) \
                           .str.split() \
                           .apply(lambda x: [float(num) for num in x])
# 拆分到三列
df[['Negative', 'Neutral', 'Positive']] = pd.DataFrame(df['scores'].tolist(), index=df.index)

方法二:正则表达式直接提取(更高效)

利用正则直接从字符串中提取三个概率值,一步生成目标列:

# 提取浮点数并转换为数值类型
df[['Negative', 'Neutral', 'Positive']] = df['scores'] \
    .str.extract(r'(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)') \
    .astype(float)

错误原因说明

  • 第一次尝试的df.scores.tolist()失效,是因为scores列的元素是字符串(而非列表对象),转换后得到的是字符串列表,无法直接生成3列DataFrame。
  • 后续用split的方法出错,是因为使用了错误的分隔符(~而非空格),且部分场景下分割后的元素数量不固定,导致列长度不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:40:23