Python PANDAS:Groupby转换首次发生条件

时间:2017-12-27 22:18:10

标签: python pandas pandas-groupby

我有以下通用格式的数据框:

customer_id,transaction_dt,product,price,units
1,2004-01-02 00:00:00,thing1,25,47
1,2004-01-17 00:00:00,thing2,150,8
2,2004-01-29 00:00:00,thing2,150,25
3,2017-07-15 00:00:00,thing3,55,17
3,2016-05-12 00:00:00,thing3,55,47
4,2012-02-23 00:00:00,thing2,150,22
4,2009-10-10 00:00:00,thing1,25,12
4,2014-04-04 00:00:00,thing2,150,2
5,2008-07-09 00:00:00,thing2,150,43
5,2004-01-30 00:00:00,thing1,25,40
5,2004-01-31 00:00:00,thing1,25,22
5,2004-02-01 00:00:00,thing1,25,2

我按相关字段按升序排序。现在我想弄清楚如何检查组内的条件并仅在第一次出现时创建新的指示器标志。作为一个玩具示例,我试图弄清楚这样的事情开始:

conditions = ((df['units'] > 20) | (df['price] > 50)

df['flag'] = df[conditions].groupby(['customer_id']).transform()

非常欢迎任何有关如何最好地制定此方法的帮助!

1 个答案:

答案 0 :(得分:1)

假设您希望在您定义的分组中按customer_id按时间顺序排列,可以使用querygroupbyfirst

(
df.sort_values("transaction_dt")
  .query("units > 20 & price > 50")
  .groupby("customer_id")
  .first()
)

注意:您提供的示例数据实际上并没有为您指定的过滤器提供多个customer_id条目,但语法在两种情况下都有效。