假设我有以下几点:
数据帧:
id endId startId ownerId value
1 50 50 10 105
2 51 50 10 240
3 52 50 10 420
4 53 53 10 470
5 40 40 11 320
6 41 40 11 18
7 55 55 12 50
8 57 55 12 412
9 59 55 12 398
10 60 57 12 320
我要做的是对endId位于同一ownerId的当前startId和当前endId之间的所有“value”列求和。你知道吗
输出应为:
id endId startId ownerId value output
1 50 50 10 105 105 # Nothing between 50 and 50
2 51 50 10 240 345 # Found 1 record (endId with id 1)
3 52 50 10 420 765 # Found 2 records (endId with id 1 and 2)
4 53 53 10 470 470 # Nothing else between 53 and 53
5 40 40 11 320 320 # Reset because Owner is different
6 41 40 11 18 338 # Found 1 record (endId with id 5)
7 55 55 12 50 50 # ...
8 57 55 12 412 462
9 59 55 12 398 860
10 60 57 12 320 1130 # Found 3 records between 57 and 60 (endId with id 8, 9 and 10)
我试着用diff,groupby.cumsum但我不能得到我需要的。。。你知道吗
我将df复制到df2,以保留原始数据。 我建议你把任务分成两步:
打印逻辑:
我很抱歉,但我还是不明白。 对于ownerId 10和11,endId和startId共享相同值的记录将在累计和上计数。 看起来还可以。但出于某种原因,你说同样的规则不适用于OwnerID12。 我知道应该考虑7到10的身份证。模式似乎是当endId和startId 匹配最高值,它发生在ID4上。你知道吗
我将使用numpy广播来标识您要查找的行:
输出为:
编辑
您可以通过以下方法避免for循环:
相关问题 更多 >
编程相关推荐