【问题标题】:writing COUNTIFS in python based on multiple conditions基于多个条件在python中编写COUNTIFS
【发布时间】:2021-10-05 17:05:33
【问题描述】:

我有一个问题,我已经能够在 excel 上解决,但也需要能够在 python 中解决这个问题。 我有一张客户表,其中包含已终止会员资格和购买历史的会员。我希望能够统计每位客户在会员资格终止前后的购买次数。

对于第一行,我使用 countifs 公式 =COUNTIFS(C:C,">"&B2,A:A,A2) 来计算客户自终止后完成的购买次数。

有没有办法在 python 中做到这一点?我试过使用 groupby 但它并没有真正输出相同的数据 here is the dataframe

【问题讨论】:

  • 请以纯文本形式复制/粘贴工作表的几行以获得帮助。

标签: python excel pandas function numpy


【解决方案1】:

Group by 是您需要的技术,可能是您做错了。 尝试以下方法计算终止后的购买次数。

select id, count(*) from table where term < purchase group by id;

如果您想统计终止前完成的购买,请将termpurchase 替换为列名,将&lt; 替换为&gt;

对应SQL语句的pandas查询是

df[df['Membership Termination date'] < df['Purchase date']].groupby('ID').size()

【讨论】:

  • 这看起来更像 SQL 而不是 pandas
  • @sammywemmy 我已经为给定的 SQL 语句添加了 pandas 查询。
猜你喜欢
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2019-09-04
相关资源
最近更新 更多