计算d之前具有相同ID的出现次数

2024-04-26 14:08:55 发布

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

我有一个带有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})

输入数据帧:

^{pr2}$

期望输出:

    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

Tags: importidpandasdf列表数量dateas
1条回答
网友
1楼 · 发布于 2024-04-26 14:08:55

groupbyid和{}:

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的影响:

^{pr2}$

或者(正如@Scott所说)
使用assign可获得以下一行程序:

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

相关问题 更多 >