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

如何按指定列数分组重塑转置后的pandas DataFrame

实现代码

你可以通过如下自定义函数实现需求,支持灵活调整分组列数:

import pandas as pd

def stack_by_column_group(df, group_size):
    group_list = []
    # 按指定步长拆分列
    for start_idx in range(0, df.shape[1], group_size):
        # 截取当前分组的列,重置列名保证拼接对齐
        current_group = df.iloc[:, start_idx:start_idx+group_size]
        current_group.columns = range(current_group.shape[1])
        group_list.append(current_group)
    # 纵向拼接所有分组
    return pd.concat(group_list)

# 你的原有业务代码
d = {'col1': [1, 2, 3 ,4 ,5, 5, 6, 5], 'col2': [3, 4, 3 ,4 , 5, 6 , 6, 5], 'col3': [5, 6, 3 ,4 , 5, 6 ,6, 5], 'col4': [7, 8, 3 , 4 , 5, 4 , 6, 4], }
df = pd.DataFrame(data=d).T

# 调用函数,示例按每组2列堆叠
output_df = stack_by_column_group(df, group_size=2)
print(output_df)

说明

  • 调整group_size参数即可修改每组的列数,例如传入3就会按每3列一组拆分后纵向堆叠
  • 若总列数无法被group_size整除,最后一组会自动保留剩余的所有列,无需额外处理边界情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:45:05