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

如何在Pandas中合并相邻行并批量重命名列?

Pandas DataFrame行合并与列重命名解决方案

1. 行两两横向合并

通过索引提取偶数行和奇数行,再横向拼接即可得到10行2088列的结果:

import pandas as pd

# 假设原始数据存储在变量df中
# 提取偶数索引行(0、2、4...18)作为X组
x_group = df.iloc[::2, :].reset_index(drop=True)
# 提取奇数索引行(1、3、5...19)作为Y组
y_group = df.iloc[1::2, :].reset_index(drop=True)

# 横向拼接两组数据,axis=1表示按列合并
merged_df = pd.concat([x_group, y_group], axis=1)

说明:reset_index(drop=True)是为了重置两组数据的索引为0-9,避免因原索引不连续导致拼接错位。

2. 批量重命名列

生成对应格式的列名列表,直接赋值给DataFrame的columns属性即可:

# 生成X前缀列名(X0到X1043)
x_columns = [f"X{i}" for i in range(1044)]
# 生成Y前缀列名(Y0到Y1043)
y_columns = [f"Y{i}" for i in range(1044)]

# 合并列名并赋值
merged_df.columns = x_columns + y_columns

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:30:51