设df是带有两列索引的布尔值的数据格式。我想计算每个id的值。例如,这就是它对这一具体情况的看法。
value consecutive
id Week
1 1 True 1
1 2 True 2
1 3 False 0
1 4 True 1
1 5 True 2
2 1 False 0
2 2 False 0
2 3 True 1这是我的解决方案
def func(id,week):
M = df.loc[id]
M= df.loc[id][:week+1]
consecutive_list = list()
S=0
for index,row in M.iterrows():
if row['value']:
S+=1
else:
S=0
consecutive_list.append(S)
return consecutive_list[-1]然后,我们以下列方式生成列“连续”作为列表:
Consecutive_list = list()
for k in df.index:
id = k[0]
week=k[1]
Consecutive_list.append(func(id,week))
df['consecutive'] = Consecutive_list我想知道是否有更多的毕达通的方法来做到这一点。
编辑:我写了“连续”一栏,以显示我期望的是什么。
发布于 2022-04-12 03:17:00
如果您试图将连续列添加到df中,则应该可以这样做:
df.assign(consecutive = df['value'].groupby(df['value'].diff().ne(0).cumsum()).cumsum())输出:
value consecutive
1 a True 1
b True 2
2 a False 0
b True 1
3 a True 2
b False 0
4 a False 0
b True 1https://stackoverflow.com/questions/71836182
复制相似问题