{"categ": [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1],
"value": [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1],
"Run_count": [0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 4, 4, 0, 0, 0, 0, 5, 5, 0, 0, 6],
"currentResults": [0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 0, 0, 5, 5, 5, 5, 6, 6, 6],
"desiredResults": [0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 0, 0, 0, 0, 1, 1, 2, 2, 2],
})
data['Run_count'] = data['value'].where(data['value'].eq(1)).dropna().groupby(data['value'].where(data['value'].eq(1)).isna().cumsum()).ngroup()+1
data['currentResults'] = np.where(data['categ']==1,data['Run_count'].bfill(),0)
我基本上已经实现了目标数据,即在data['currentResults']
中展示的内容。然而,我还想达成一个新的目标,在索引值为15且 df['categ']
为 1 的位置上,我想让 data['desiredCount']
中的计数重新开始。由于在索引 13 至 14 处,df['categ']
的值为 0,目前在索引为 15 时,data['currentResults']
继续计数为 "5",而我希望计数从 1 重新开始。
我认为根据我当前的代码,最容易实现这个目标的方式可能是基于某些条件在 “Run_count” 列中重置/重启计数器。
附图展示了我希望在 “desiredResults” 列中实现的效果:

简而言之,我想要在遇到连续的 categ
为 0 的行之后,当再次遇到 categ
变为 1 时,对应的 desiredResults
计数值能从 1 开始重新计数。