python - Pandas countif 有条件
问题描述
我在 pandas 中有一个具有唯一事件键、人员键、日期和其他各种列的数据集。我正在尝试添加一个新列,该列将在该行的日期之前为该人提供事件计数。我一直在搜索,但我只找到设置标准的结果(即 df ['x']=df [df ['date']<'2018-06-01'] 日期不会随每一行动态变化)或对于需要很长时间的 .apply (function) 方法。
我正在考虑将 df 放入一个 sqlite db,然后将表连接到自身,然后是 count distinct case 语句。下面的例子。但是,我随后需要做一些额外的操作,我认为在 python 中必须有一种更快的方法来做到这一点。有什么建议么?
Sample data in df- dates repeat and not in order. Multiple people can be on one date and a person can have multiple events on a single date.
[Event, person, date]
[1,1,2018-01-03]
[2,1,2018-01-01]
[3,1,2018-01-02]
[4,2,2018-01-04]
[5,2,2018-01-05]
Desired output
[Event, person, date, count of evnt]
[1,1,2018-01-03, 2]
[2,1,2018-01-01, 0]
[3,1,2018-01-02, 1]
[4,2,2018-01-04, 0]
[5,2,2018-01-05, 1]
对不起格式,我在我的手机上。
例子:
假设字段是 evebt, person, date 我会
Select event,
person,
date,
Count (distinct (case when ((t2.date less than
t1.date) And (t2.person=t1.person))
Then t2.event else null end)) event_count
From t1
Left outer join t1 as t2 on (t2.event=t1.event)
Group by event, person, date.
解决方案
推荐阅读
- docker - 构建 Dockerfile 时 AzureDevops 找不到 csproj 文件
- java - 无法在 http://localhost:8080/business-central 上启动 jbpm
- amadeus - 自助预订流程,包括付款
- pyspark - 如何在 pyspark 的数据透视表中添加/包含标题行和总计行?
- ruby-on-rails - Spree 自定义控制器中的实例变量 - 自动分配?
- python - 是否有一种方法/算法可以从给定数字的素数生成唯一整数?
- asp.net-core - 取消令牌有时不会取消 HttpRequest
- .net - 无法将带有 axious 的数组列表从 vuejs 发布到 .net Core
- regex - 尝试在从前面/后面排除时进行匹配 - Eclipse Negative Lookahead 没有按我预期的那样工作
- regex - 黑色 --exclude 参数不排除所需文件