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

Python中为Pandas DataFrame新增列实现按n行拆分分组的方法

实现方法

你只需要一行代码就能完成需求,不需要写循环遍历,逻辑为对从0开始的行序号做整数除法后加1,直接生成Group列:

import pandas as pd
import numpy as np

# 构造示例DataFrame
df = pd.DataFrame({
    'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'],
    'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'],
    'Value': [11, 8, 10, 15, 110, 60, 100, 40]
})

n = 3 # 每个分组的行数
# 新增Group列
df['Group'] = np.arange(len(df)) // n + 1

如果不想依赖numpy,也可以用pandas原生写法:

# 适用默认从0开始的连续整数索引场景
df['Group'] = df.index // n + 1

# 如果行索引不是连续的0开头整数,用这个写法保证逻辑正确
df['Group'] = df.reset_index(drop=True).index // n + 1

运行后输出的df和你期望的结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:09:03