2024-09-28 21:03:36 发布
网友
假设我有以下2pandas个数据帧:
pandas
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循环来实现这一点。然而,我想知道是否有更优雅的解决方案
for
您可以使用shift()检查a后面是否跟有b和向量化的&,然后用sum来计算真值:
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
您可以使用
shift()
检查a
后面是否跟有b
和向量化的&
,然后用sum
来计算真值:创造性解决方案:
说明:
相关问题 更多 >
编程相关推荐