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

如何按指定行数将单列DataFrame拆分为多列

拆分单列DataFrame为指定行数的多列

需求说明

现有仅含Column A的单列DataFrame:

Column A
Cell 1
Cell 2
Cell 3
Cell 4
Cell 5
Cell 6
Cell 7
Cell 8

需按指定行数(示例为2行)拆分,生成如下多列结构:

Column AColumn BColumn CColumn D
Cell 1Cell 3Cell 5Cell 7
Cell 2Cell 4Cell 6Cell 8

实现方法(基于Pandas)

1. 创建示例数据

import pandas as pd

df = pd.DataFrame({'Column A': ['Cell 1', 'Cell 2', 'Cell 3', 'Cell 4', 'Cell 5', 'Cell 6', 'Cell 7', 'Cell 8']})

2. 方法一:用Numpy Reshape快速重塑

指定每列行数n,通过数组重塑直接转换结构:

n = 2  # 设定每列行数
# 将数据转为数组后重塑为n行,自动计算列数,再转置得到目标结构
reshaped_data = df['Column A'].values.reshape(n, -1).T
# 转为DataFrame并命名列
result_df = pd.DataFrame(reshaped_data, columns=[f'Column {chr(65 + i)}' for i in range(reshaped_data.shape[1])])

3. 方法二:用Pandas分组转置

通过分组键将数据拆分后转为列:

n = 2
# 添加分组标识,每n个元素为一组
df['group'] = df.index // n
# 分组转置并重新命名列
result_df = df.pivot(columns='group', values='Column A') \
              .rename(columns=lambda x: f'Column {chr(65 + x)}') \
              .reset_index(drop=True)

4. 处理行数无法被整除的情况

如果原数据行数不是n的整数倍,可先填充NaN至整数倍后再处理:

n = 2
pad_length = (n - len(df) % n) % n
df_padded = pd.concat([df, pd.DataFrame({'Column A': [None]*pad_length})], ignore_index=True)

# 复用Reshape方法
reshaped_data = df_padded['Column A'].values.reshape(n, -1).T
result_df = pd.DataFrame(reshaped_data, columns=[f'Column {chr(65 + i)}' for i in range(reshaped_data.shape[1])])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:16:08