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

如何添加每4行一组进行编号的新列?

实现方法

假设你使用Python的pandas库处理数据,以下是最简洁的实现方式:

步骤1:准备数据

先构造示例中的DataFrame:

import pandas as pd

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

步骤2:生成新列new_col

利用整数除法按每4行一组分配组号,代码如下:

df['new_col'] = (df.index // 4) + 1

如果你的数据索引不是连续的0开始序列,可以改用行号计数:

import numpy as np

df['new_col'] = (np.arange(len(df)) // 4) + 1

结果验证

执行后得到的DataFrame完全符合你的需求:

data  new_col
0     1        1
1     2        1
2     4        1
3     6        1
4     8        2
5     9        2
6     7        2
7     5        2
8     3        3
9     2        3

原理说明

  • df.index // 4 或 np.arange(len(df)) // 4:将行索引(或行号)按每4个为一组做整数除法,得到每组的基准编号(0、0、0、0、1、1、1、1、2、2...)
  • 加1是为了让组号从1开始,而非0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:57:18