[英]Pandas: Group-by and Aggregate Column 1 with Condition from Column 2
I'm trying to move from R & dplyr into python and Pandas for some projects, and I'm hoping to figure out how to replicate common coding strategies I used with dplyr. 我正在尝试从R&dplyr迁移到某些项目的python和Pandas中,并且希望弄清楚如何复制与dplyr一起使用的常见编码策略。
One common one is that I'll group by a particular column, then calculate a derived column that involves a condition from some third column. 一种常见的情况是,我将按特定的列分组,然后计算一个涉及第三列中条件的派生列。 Here's a simple example:
这是一个简单的例子:
dat = data.frame(user = rep(c("1",2,3,4),each=5),
cancel_date = rep(c(12,5,10,11), each=5)
) %>%
group_by(user) %>%
mutate(login = sample(1:cancel_date[1], size = n(), replace = T)) %>%
ungroup()
- --
Source: local data frame [6 x 3]
user cancel_date login
1 1 12 3
2 1 12 9
3 1 12 12
4 1 12 4
5 1 12 2
6 2 5 4
In this data frame, I'd like to calculate how many logins each user had three months before they cancelled. 在此数据框中,我想计算每个用户在取消前三个月的登录次数。 In dplyr, this is simple:
在dplyr中,这很简单:
dat %>%
group_by(user) %>%
summarise(logins_three_mos_before_cancel = length(login[cancel_date-login>=3]))
user logins_three_mos_before_cancel
1 1 4
2 2 1
3 3 5
4 4 3
But I'm a bit stumped at how to do this pandas. 但是我对如何做这只熊猫有些困惑。 As far as I can tell, aggregate only applies a function on a given grouped column, and I don't know how to get it to apply a function that involves multiple columns.
据我所知,聚合仅在给定的分组列上应用函数,并且我不知道如何使它应用涉及多个列的函数。
Here's that same data in pandas: 这是熊猫中的相同数据:
d = { 'user' : np.repeat([1,2,3,4],5),
'cancel_date' : np.repeat([12,5,10,11],5),
'login' : np.array([3, 9, 12, 4, 2, 4, 3, 5, 5, 1, 3, 5, 4, 6, 3, 3, 5, 10, 7, 10])
}
pd.DataFrame(data=d)
I hope I followed your R, but do you mean this? 我希望我遵循了您的R,但这是您的意思吗?
>> df[df.cancel_date - df.login >= 3].user.value_counts().sort_index()
1 4
2 1
3 5
4 3
dtype: int64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.