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

如何在Pandas DataFrame中将带标题项目符号的字符串转为两列并清理内容

解决方法

下面是实现需求的具体步骤和代码:

首先,我们需要把原始字符串拆解成标题和对应的内容条目,再整理成目标格式的DataFrame:

import pandas as pd

mystr=' Here is a summary of the key financial trends for XYZ based on the earnings call transcript:\n\nHeader 0:\n- Q4 revenue was $2.7 billion, down 12% sequentially and 16% year-over-year due to broad-based weakness\n- Gross margin was 70.2%, down sequentially and year-over-year\n- Operating margin was 44.7%. FY2023 operating margin was 48.9%, down 50 basis points  \n- Q4 EPS was $2.01, slightly above outlook\n\nHeader 1:  \n- Q4 inventory decreased by $70 million sequentially to 188 days\n- Reduced Q4 OpEx by $60M sequentially through discretionary cuts and lower variable comp\n\nHeader 2:\n- Industrial revenue down 19% sequentially and 20% year-over-year in Q4 on broad-based weakness\n- Automotive revenue down slightly sequentially, up 14% year-over-year in Q4\n- Communications revenue down 6% sequentially, 32% year-over-year in Q4  \n- Consumer revenue down 6% sequentially, 28% year-over-year in Q4\n\nHeader 3:\n- Q1 revenue guidance $2.5 billion +/- $100 million. Expect all end markets down sequentially\n- Expect inventory correction to taper through 1H of FY2024'

# 1. 剥离开头无关内容,按\n\n分割成独立的标题-内容块
blocks = mystr.split('\n\n')[1:]

# 2. 遍历每个块,提取并清理标题和内容
data = []
for block in blocks:
    lines = block.split('\n')
    # 清理标题:移除末尾冒号和前后多余空格
    header = lines[0].strip().rstrip(':')
    # 清理内容:移除每个条目开头的项目符号和前后空白
    items = [line.strip().lstrip('- ').strip() for line in lines[1:] if line.strip()]
    # 每个内容条目对应一行数据,和标题配对存入列表
    for item in items:
        data.append({'标题': header, '内容': item})

# 3. 转换为Pandas DataFrame
df = pd.DataFrame(data)
print(df)

关键步骤说明:

  • 拆分标题块:用\n\n分割字符串后,丢弃第一个无关的引言部分,剩下的就是每个标题对应的内容组。
  • 标题清理:通过strip()移除前后空格,rstrip(':')去掉标题末尾的冒号,让标题格式更整洁。
  • 内容清理:遍历每个内容行,先移除前后空白,再剥离开头的- 符号,确保内容干净无多余标记。
  • 构建数据结构:将每个标题和对应的内容条目一一配对,存入字典列表,最后转换为DataFrame,得到每行对应一个标题+一条内容的结构。

运行代码后即可得到符合预期的DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:44:51