基于另一个系列的大熊猫高效分组



我需要根据DataFrame中的另一个布尔列进行分组操作。在一个例子中很容易看到:我有以下DataFrame

    b          id   
0   False      0
1   True       0
2   False      0
3   False      1
4   True       1
5   True       2
6   True       2
7   False      3
8   True       4
9   True       4
10  False      4

并希望获得一列,如果b列为 True,并且对于给定id它是最后一次为 True,则其元素为 True:

    b          id    lastMention
0   False      0     False
1   True       0     True
2   False      0     False
3   False      1     False
4   True       1     False
5   True       2     True
6   True       3     True
7   False      3     False
8   True       4     False
9   True       4     True
10  False      4     False

我有一个代码可以实现这一点,尽管效率低下:

def lastMentionFun(df):
    b = df['b']
    a = b.sum()
    if a > 0:
        maxInd = b[b].index.max()
        df.loc[maxInd, 'lastMention'] = True
    return df
df['lastMention'] = False
df = df.groupby('id').apply(lastMentionFun)

有人可以提出什么是正确的pythonic方法来做到这一点吗?

您可以

先过滤列 b 中 True 的值,然后获取max索引值,其中包含groupby和聚合max

print (df[df.b].reset_index().groupby('id')['index'].max())
id
0    1
1    4
2    6
4    9
Name: index, dtype: int64

然后将索引值False的值替换为 loc

df['lastMention'] = False
df.loc[df[df.b].reset_index().groupby('id')['index'].max(), 'lastMention'] = True
print (df)
        b  id  lastMention
0   False   0        False
1    True   0         True
2   False   0        False
3   False   1        False
4    True   1         True
5    True   2        False
6    True   2         True
7   False   3        False
8    True   4        False
9    True   4         True
10  False   4        False

另一种解决方案 - 使用 groupbyapply 获取max索引值,然后使用 isin 测试索引中值的成员资格 - 输出boolean Series

print (df[df.b].groupby('id').apply(lambda x: x.index.max()))
id
0    1
1    4
2    6
4    9
dtype: int64
df['lastMention'] = df.index.isin(df[df.b].groupby('id').apply(lambda x: x.index.max()))
print (df)
        b  id lastMention
0   False   0       False
1    True   0        True
2   False   0       False
3   False   1       False
4    True   1        True
5    True   2       False
6    True   2        True
7   False   3       False
8    True   4       False
9    True   4        True
10  False   4       False

不确定这是否是最有效的方法,但它只使用内置函数(主要的是"cumsum",然后是 max 来检查它是否等于最后一个 - pd.merge 只是用来把最大值放回表中,也许有更好的方法?

df['cum_b']=df.groupby('id', as_index=False).cumsum()
df = pd.merge(df, df[['id','cum_b']].groupby('id', as_index=False).max(), how='left', on='id', suffixes=('','_max'))
df['lastMention'] = np.logical_and(df.b, df.cum_b == df.cum_b_max)

附言您在示例中指定的数据帧从第一个代码段到第二个代码段略有变化,我希望我正确解释了您的请求!

最新更新