【发布时间】:2017-03-21 11:53:22
【问题描述】:
我需要执行一个基于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方法来快速完成这项工作吗?
【问题讨论】:
标签: python python-3.x pandas dataframe group-by