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

如何编写函数将单列文本数据拆分至对应多列?

单列文本数据拆分至多列的实现方案

问题背景

现有表格数据中所有有效信息都集中在header列,需按规则拆分到Company、price、result、date列,最终整理为目标格式。

原始数据

headerCompanypricedata
1done
2nan
3comp1
4nan
5price:222
6result:ok, 22.05.19
7nan
8done
9nan
10comp2
11nan
12price:2895
13result:no, 15.05.19
14nan
15done
16and ctr

目标格式

numCompanypriceresultdate
1Comp1222ok22.05.19
2Comp22895no15.05.19
etc

实现代码(Python + Pandas)

import pandas as pd
import numpy as np

def split_single_column_data(df):
    # 过滤无效行:排除nan、done、and ctr这类无关内容
    filtered_df = df[~df['header'].isin(['nan', 'done', 'and ctr'])].reset_index(drop=True)
    
    # 按每组3行(公司、价格、结果)拆分数据
    groups = np.array_split(filtered_df, len(filtered_df) // 3)
    
    # 提取每组数据并整理成目标结构
    result_list = []
    for idx, group in enumerate(groups, 1):
        company = group.iloc[0]['header'].capitalize()
        price = group.iloc[1]['header'].split(':')[1]
        result_part = group.iloc[2]['header'].split(':')[1].split(', ')
        result = result_part[0]
        date = result_part[1]
        
        result_list.append({
            'num': idx,
            'Company': company,
            'price': price,
            'result': result,
            'date': date
        })
    
    # 转换为目标格式的DataFrame
    return pd.DataFrame(result_list)

# 测试示例
if __name__ == '__main__':
    # 构造原始数据
    raw_data = {
        'header': ['done', 'nan', 'comp1', 'nan', 'price:222', 'result:ok, 22.05.19',
                   'nan', 'done', 'nan', 'comp2', 'nan', 'price:2895', 'result:no, 15.05.19',
                   'nan', 'done', 'and ctr'],
        'Company': ['']*16,
        'price': ['']*16,
        'data': ['']*16
    }
    raw_df = pd.DataFrame(raw_data)
    
    # 执行拆分函数
    final_df = split_single_column_data(raw_df)
    print(final_df)

代码说明

  • 过滤无效行:直接排除已知的无关标识行,仅保留有效数据
  • 分组处理:根据每组数据固定3行的规律,将过滤后的数据按3行一组拆分
  • 数据提取:针对每组内的行,分别提取公司名(首字母大写)、价格(拆分冒号后的内容)、结果和日期(拆分冒号后再按逗号分隔)
  • 结果整理:将每组提取的数据构造成字典,最终转换为目标格式的DataFrame

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:21:34