Python 统计日期之前具有相同ID的事件数

Python 统计日期之前具有相同ID的事件数,python,pandas,Python,Pandas,我有一个带有ID和日期的事件列表。我想知道的是过去使用该id发生的事件数。例如: import pandas as pd rng = pd.date_range('1/1/2018', periods=10, freq='D') df = pd.DataFrame({'id':[1,1,1,2,2,3,3,3,3,3], 'date':rng}) 输入数据帧: date id 0 2018-01-01 1 1 2018-01-02 1 2 2018-01-

我有一个带有ID和日期的事件列表。我想知道的是过去使用该id发生的事件数。例如:

import pandas as pd

rng = pd.date_range('1/1/2018', periods=10, freq='D')
df = pd.DataFrame({'id':[1,1,1,2,2,3,3,3,3,3], 'date':rng})
输入数据帧:

    date       id
0   2018-01-01  1
1   2018-01-02  1
2   2018-01-03  1
3   2018-01-04  2
4   2018-01-05  2
5   2018-01-06  3
6   2018-01-07  3
7   2018-01-08  3
8   2018-01-09  3
9   2018-01-10  3
期望输出:

    date       id   occurrences
0   2018-01-01  1   0
1   2018-01-02  1   1
2   2018-01-03  1   2
3   2018-01-04  2   0
4   2018-01-05  2   1
5   2018-01-06  3   0
6   2018-01-07  3   1
7   2018-01-08  3   2
8   2018-01-09  3   3
9   2018-01-10  3   4
通过循环行很容易做到这一点,但我想知道是否有更有效的方法来做到这一点。以下是通过行循环的解决方案:

occurrences = []
for index, row in df.iterrows():
    occurrences.append(df[(df['id'] == row['id']) & (df['date'] < row['date'])].shape[0])

df['occurrences'] = occurrences
出现次数=[]
对于索引,df.iterrows()中的行:
事件。追加(df[(df['id']==行['id'])和(df['date']<行['date'])。形状[0])
df['acentations']=事件

groupby
id
cumcount

df.groupby('id').cumcount()

0    0
1    1
2    2
3    0
4    1
5    0
6    1
7    2
8    3
9    4

注意
影响您的df:

df['occurences'] = df.groupby('id').cumcount()
或者(正如@Scott所说)
使用“指定”获取以下一行:

df.assign(occurences = df.groupby('id').cumcount())
结果

print(df)
        date  id  occurences
0 2018-01-01   1           0
1 2018-01-02   1           1
2 2018-01-03   1           2
3 2018-01-04   2           0
4 2018-01-05   2           1
5 2018-01-06   3           0
6 2018-01-07   3           1
7 2018-01-08   3           2
8 2018-01-09   3           3
9 2018-01-10   3           4

分组依据
id
cumcount

df.groupby('id').cumcount()

0    0
1    1
2    2
3    0
4    1
5    0
6    1
7    2
8    3
9    4

注意
影响您的df:

df['occurences'] = df.groupby('id').cumcount()
或者(正如@Scott所说)
使用“指定”获取以下一行:

df.assign(occurences = df.groupby('id').cumcount())
结果

print(df)
        date  id  occurences
0 2018-01-01   1           0
1 2018-01-02   1           1
2 2018-01-03   1           2
3 2018-01-04   2           0
4 2018-01-05   2           1
5 2018-01-06   3           0
6 2018-01-07   3           1
7 2018-01-08   3           2
8 2018-01-09   3           3
9 2018-01-10   3           4

您是否尝试过按
id
date
然后cumsum排序进行分组?您是否尝试过按
id
然后cumsum排序进行分组?
df.assign(occurences=df.groupby('id').cumcount())
one-liner.Can
df['occurences']=df.groupby('id').cumcount())。这也是一个单行程序。
df.assign(occurrences=df.groupby('id').cumcount())
one-liner.Can do
df['occurrences']=df.groupby('id').cumcount()。那也是一条单行线。