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

Python:将日期:价格列表转换为多行数据

高效拆分日期-价格对并转换为多行结构

处理思路

用pandas的矢量化操作替代逐行字符串处理,大幅提升效率,步骤如下:

  1. 构造/导入原始数据
import pandas as pd
import ast

# 模拟原始表格数据
df = pd.DataFrame({
    'Id': ['001', '002'],
    'Prices': ['["March:59", "April:64", "May:62"]', '["Jan:55", "Feb:58"]']
})
  1. 解析字符串列表为实际列表
    把Prices列中字符串格式的列表转为Python原生列表,方便后续拆分:
df['Prices'] = df['Prices'].apply(ast.literal_eval)
  1. 将列表元素拆分为单独行
    用explode方法快速将每个列表元素展开为独立行:
df_exploded = df.explode('Prices', ignore_index=True)
  1. 矢量化拆分日期与价格
    通过str.split结合expand=True直接生成两列,这一步是矢量化操作,比逐行处理效率高数倍:
# 拆分日期和价格,自动生成两列
df_exploded[['date', 'price']] = df_exploded['Prices'].str.split(':', expand=True)

# 整理最终结果
result = df_exploded.drop('Prices', axis=1).rename(columns={'Id': 'id'})

最终结果

iddateprice
001March59
001April64
001May62
002Jan55
002Feb58

额外优化

如果Prices列存在不符合日期:价格格式的元素,可提前过滤:

df_exploded = df_exploded[df_exploded['Prices'].str.contains(':')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:37:40