如何识别两行中的特定事件并计算

2024-09-28 21:03:36 发布

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

假设我有以下2pandas个数据帧:

id | userid | type 
1  | 20     | a  
2  | 20     | a
3  | 20     | b
4  | 21     | a  
5  | 21     | b
6  | 21     | a
7  | 21     | b
8  | 21     | b

我希望获得每个用户“b跟随a”的次数,并获得如下所示的新数据帧:

userid | b_follows_a
20     | 1
21     | 2

我知道我可以使用for循环来实现这一点。然而,我想知道是否有更优雅的解决方案


Tags: 数据用户idfortype解决方案次数userid
2条回答

您可以使用shift()检查a后面是否跟有b和向量化的&,然后用sum来计算真值:

df.groupby('userid').type.apply(lambda x: ((x == "a") & (x.shift(-1) == "b")).sum()).reset_index()

#userid type
#0   20    1
#1   21    2

创造性解决方案:

In [49]: df.groupby('userid')['type'].sum().str.count('ab').reset_index()
Out[49]:
   userid  type
0      20     1
1      21     2

说明:

In [50]: df.groupby('userid')['type'].sum()
Out[50]:
userid
20      aab
21    ababb
Name: type, dtype: object

相关问题 更多 >