首页 > 解决方案 > 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.

标签: pythonsqlpandas

解决方案


推荐阅读