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

如何将pandas DataFrame中存储Series的列拆分为多个独立列

实现方案

根据Col1列的实际存储类型,选对应方法即可,无需手写逐行for循环,执行效率远高于自定义遍历逻辑:

  • 如果你打印df['Col1'][0]输出带引号,和你给出的样例一样是文本内容,属于字符串存储场景,用正则提取方案
  • 如果type(df['Col1'][0])返回pandas.core.series.Series,属于真实Series对象存储场景,用apply转换方案

字符串存储场景处理代码

import pandas as pd

# 正则匹配所有「指标名+对应浮点值」的组合
extract_pairs = df["Col1"].str.extractall(r"(\w+)\s+(\d+\.\d+)")
# 将提取到的数值转为浮点类型
extract_pairs[1] = extract_pairs[1].astype(float)
# 透传为宽表结构
wide_df = extract_pairs.droplevel("match").pivot(columns=0, values=1)
# 合并Date列得到最终结果
result = pd.concat([df["Date"], wide_df], axis=1)

Series对象存储场景处理代码

import pandas as pd

# 逐行将Series转为DataFrame列后直接合并
result = pd.concat([df["Date"], df["Col1"].apply(pd.Series)], axis=1)

输出效果

两种方法运行后输出和你预期完全一致:

Date  Amt_Mean  Amt_Med  Amt_Std
0 2022-01-02    2022.0      5.0    877.0
1 2022-01-03    2025.0     75.0     27.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:12:39