在 pandas 中使用布尔值分组值

Groupby values using boolean in pandas

df['check'] = ((df['id'] == 123) & (df['date1'] >= date1)) | ((df['id'] == 456) & (df['date2'] >= date2))

present = df.groupby(['id', 'month', 'check'])['userid'].nunique().reset_index(name="usercount")

这是我的代码,因此我的预期输出必须在 usercount 列中包含每月唯一用户数 按 id 分组。我在 groupby.

中使用了 idmonthcheck

check 列的类型为 bool,基于我的代码的第一行,但是当我从 present 数据框获得输出时,用户被计算为 [=16] =] 值为 True,也有 False.

实际上,它应该统计在check列中只有True的用户。

帮我解决这个问题

您需要按 check 列按 boolean indexing 过滤,而不是传递给 groupby 中的 by 参数:

#first convert datetimes to start of months
df['month'] = df['month'].dt.floor('d') - pd.offsets.MonthBegin(1)
print (df)
   check      month   id userid
0   True 2019-06-01  123      a
1  False 2019-02-01  123      b
2  False 2019-01-01  123      c
3  False 2019-02-01  123      d
4   True 2019-06-01  123      e
5   True 2020-07-01  123      f
6   True 2020-07-01  123      g
7   True 2020-06-01  123      h

print (df[df['check']])
   check      month   id userid
0   True 2019-06-01  123      a
4   True 2019-06-01  123      e
5   True 2020-07-01  123      f
6   True 2020-07-01  123      g
7   True 2020-06-01  123      h

present = (df[df['check']].groupby(['id', 'month'])['userid']
                          .nunique()
                          .reset_index(name="usercount"))
print (present)
    id      month  usercount
0  123 2019-06-01          2
1  123 2020-06-01          1
2  123 2020-07-01          2