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

如何用.stack()和.str.split()按列名相似性堆叠Pandas DataFrame?

使用.stack()和.str.split()实现DataFrame格式转换

问题描述

现有经过滚动计算后的Pandas DataFrame(df1),其列名格式为col_X_rolling_daily或col_X_rolling_weekly,需将其转换为以分位数(quantile)为索引,包含各列滚动值分位数、类型(Type)和时间周期(timeframe)的目标格式。

解答

完全可以通过str.split()和stack()结合其他Pandas函数实现该转换需求,具体步骤如下:

步骤1:拆分列名并设置多级列索引

利用str.split()将列名按_rolling_拆分,得到原始列名和时间周期的二级列索引:

# 拆分列名,生成(col, timeframe)的多级列索引
df1.columns = df1.columns.str.split('_rolling_', expand=True)
df1.columns.set_names(['col', 'timeframe'], inplace=True)

步骤2:使用stack()转换为长格式

通过stack()将时间周期维度从列索引转为行索引,得到长格式数据:

# 堆叠timeframe维度,转为长格式
df_long = df1.stack(level='timeframe').reset_index()
df_long.columns = ['date', 'timeframe', 'col', 'value']

步骤3:计算各分组的分位数

按时间周期和原始列分组,计算指定分位数(如0.01、0.03、0.05、0.10):

# 定义需要计算的分位数
quantiles = [0.01, 0.03, 0.05, 0.10]
# 分组计算分位数,并将原始列转为宽格式
df_quantiles = df_long.groupby(['timeframe', 'col'])['value'].quantile(quantiles).unstack(level='col')

步骤4:调整格式匹配目标结构

重置索引、添加Type列,并调整列顺序和索引:

# 重置索引并添加Type列
df_quantiles = df_quantiles.reset_index()
df_quantiles['Type'] = 'pct'

# 重命名列并调整顺序
df_quantiles.columns = ['timeframe', 'quantile', 'col_A_rolling', 'col_B_rolling', 'col_C_rolling', 'Type']
df_final = df_quantiles[['col_A_rolling', 'col_B_rolling', 'col_C_rolling', 'Type', 'timeframe']]

# 设置quantile为索引
df_final.set_index('quantile', inplace=True)

最终得到的df_final即为符合要求的目标格式DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:10:22