pandas data fram中前几行的累计计数

2024-06-26 03:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

 date   ID   flag
 Apr1   1    True
 Apr2   2    True
 May1   1    True
 May1   1    False
 May2   1    True

需要前几天(包括那天)的ID的累计计数,其中标志是True,如下所示:

^{pr2}$

我尝试了布尔蒙版和cumsum(),但没有让它起作用。建议?在


Tags: 数据idfalsetruedate标志建议flag
2条回答

这似乎是你需要的:

df['count'] = df.groupby(by=['ID'])['flag'].cumsum().astype(int)

输出:

^{pr2}$

这不是你要找的cumcount和{}

df.groupby('ID').flag.cumsum().astype(int)
Out[362]: 
0    1
1    1
2    2
3    2
4    3
Name: flag, dtype: int32

相关问题 更多 >