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

如何将Pandas DataFrame中不同长度列表转为单列多行数据?

问题描述

我在Pandas中有如下表格:

  • Date列均为周五,因节假日等可能不连续;
  • Performance列是对应下周业绩的列表,最后一行列表长度小于5(因当天是周三,仅存周一、周二数据)。

原表格:

DatePerformance
2022/01/27[0.1,0.1,0.2,0.1,0.3]
2022/02/10[0.1,0.1,0.2,0.1,0.3]
2022/02/17[0.1,0.1,0.2,0.1,0.3]
2022/02/24[0.1,0.1]

希望转换为包含实际业绩日期和对应业绩值的二维表格:

DatePerformance
2022/01/300.1
2022/01/310.1
2022/02/010.2
2022/02/020.1
2022/02/030.3
2022/02/130.1
2022/02/140.1
2022/02/150.2
......
2022/02/270.1
2022/02/280.1

曾尝试用sum合并所有列表为一维数组,但无法对应到日期列,请问如何用Python实现?

解决方案

可以通过以下步骤实现,核心是展开Performance列表的同时,生成对应的业绩日期:

  1. 将Date列转换为datetime类型,方便后续日期计算
  2. 对每一行,根据Performance列表的长度,生成从该周五之后的第一个工作日(周一)开始的连续日期
  3. 展开列表并匹配日期,最终重组为目标表格

完整代码如下:

import pandas as pd
from pandas.tseries.offsets import BDay

# 构建原始数据
data = {
    'Date': ['2022/01/27', '2022/02/10', '2022/02/17', '2022/02/24'],
    'Performance': [[0.1,0.1,0.2,0.1,0.3], [0.1,0.1,0.2,0.1,0.3], [0.1,0.1,0.2,0.1,0.3], [0.1,0.1]]
}
df = pd.DataFrame(data)

# 转换Date列为datetime类型
df['Date'] = pd.to_datetime(df['Date'])

# 定义函数:生成对应业绩日期并展开数据
def expand_row(row):
    # 计算下周一开始的日期(周五+2个工作日)
    start_date = row['Date'] + BDay(2)
    # 根据Performance列表长度生成连续工作日日期
    dates = pd.date_range(start=start_date, periods=len(row['Performance']), freq='B')
    # 返回包含日期和业绩值的DataFrame
    return pd.DataFrame({
        'Date': dates.strftime('%Y/%m/%d'),
        'Performance': row['Performance']
    })

# 对每一行应用函数,合并结果
result_df = pd.concat([expand_row(row) for _, row in df.iterrows()], ignore_index=True)

print(result_df)

代码说明

  • BDay是Pandas的工作日偏移量,自动跳过周末和节假日,确保生成的日期都是有效工作日
  • pd.date_range根据列表长度生成连续的工作日日期,完美匹配Performance列表的每个元素
  • 通过pd.concat将每行展开后的小DataFrame合并成最终的二维表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:37:44