在python中设置记录集的批次号
我在csv中有以下数据在python中设置记录集的批次号,python,python-3.x,pandas,numpy,Python,Python 3.x,Pandas,Numpy,我在csv中有以下数据 id,date,records 1,2019-03-28 01:22:12,5 2,2019-03-29 01:23:23,5 3,2019-03-30 01:28:54,5 4,2019-03-28 01:12:21,2 5,2019-03-12 01:08:11,1 6,2019-03-28 01:01:21,12 7,2019-03-12 01:02:11,1 我试图实现的是设置一个批次号,该批次号在移动和值超过15后应继续增加,移动和也应重置,因此我尝试为移动和
id,date,records
1,2019-03-28 01:22:12,5
2,2019-03-29 01:23:23,5
3,2019-03-30 01:28:54,5
4,2019-03-28 01:12:21,2
5,2019-03-12 01:08:11,1
6,2019-03-28 01:01:21,12
7,2019-03-12 01:02:11,1
我试图实现的是设置一个批次号,该批次号在移动和值超过15后应继续增加,移动和也应重置,因此我尝试为移动和值总计为15的记录创建批次
例如,如果移动总和变为15,则批次号值应增加,这将给我提供包含总值15的行
所以我想要的结果是,如果累计总和超过15-
id,date,records, moving_sum,batch_number
1,2019-03-28 01:22:12,5,5,1
2,2019-03-29 01:23:23,5,10,1
3,2019-03-30 01:28:54,5,15,1
4,2019-03-28 01:12:21,2,2,2
5,2019-03-12 01:08:11,1,1,2
6,2019-03-28 01:01:21,2,12,2
7,2019-03-12 01:02:11,1,1,3
我正在为此使用pandas,但无法重置移动和并结转之前设置的批次号 您可以使用
df.iterrows()
执行类似操作
moving = []
batch = []
cntr = 1
for idx,row in df.iterrows():
if len(moving) == 0:
moving.append(row['records'])
batch.append(cntr)
elif moving[-1] < 15:
moving.append(row['records']+moving[-1])
batch.append(cntr)
elif moving[-1] >= 15:
moving.append(row['records'])
cntr += 1
batch.append(cntr)
df['moving_sum'] = moving
df['batch_number'] = batch
id records moving_sum batch_number
0 1 5 5 1
1 2 5 10 1
2 3 5 15 1
3 4 2 2 2
4 5 1 3 2
5 6 12 15 2
6 7 1 1 3