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

如何使用Pandas重新排列DataFrame实现多行合并为一行并扩展列数?

Pandas实现DataFrame行合并重排

首先构造你给出的示例DataFrame:

import pandas as pd

df = pd.DataFrame(
    [[x]*5 for x in ['a','b','c','d','e','f']],
    index=[1,2,3,4,5,6],
    columns=['A','B','C','D','E']
)

方法一:分组拼接(灵活适配复杂场景)

  • 步骤1:生成分组标识
    每2行分为一组,用整数除法生成分组键:

    df['group'] = (df.index - 1) // 2
    
  • 步骤2:分组合并行
    对每个分组,将第二行内容拼接至第一行后方:

    def combine_rows(group):
        base_row = group.iloc[0].copy()
        add_vals = group.iloc[1].values[:5]
        return pd.concat([base_row, pd.Series(add_vals)], ignore_index=True)
    
    result = df.groupby('group').apply(combine_rows)
    
  • 步骤3:调整列名与索引

    result.columns = ['A','B','C','D','E','F','G','H','I','J']
    result.index = df.index[::2]  # 保留原分组首行索引1、3、5
    

方法二:numpy重塑(高效适配规则数据)

如果数据行数是偶数且分组规则固定,用numpy重塑更高效:

reshaped_data = df.values.reshape(3, 10)
result = pd.DataFrame(
    reshaped_data,
    index=[1,3,5],
    columns=['A','B','C','D','E','F','G','H','I','J']
)

最终得到的result结构如下:

A  B  C  D  E  F  G  H  I  J
1  a  a  a  a  a  b  b  b  b  b
3  c  c  c  c  c  d  d  d  d  d
5  e  e  e  e  e  f  f  f  f  f

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:45:51