我对R dplyr进行数据分析非常熟悉,并且正在尝试将用dplyr编写的一些代码转换为pandas.我所拥有的数据由ID列和DATE所标识的人员使用该产品.我正在尝试找出将以下R dplyr代码转换为python pandas代码的最佳方法.基本上,我将ID列分组,过滤某种类型的产品,然后添加一列(对于该组中的每一行),添加该人的最短(首次使用)日期和最长(最后使用)日期和产品.最后,我还要添加一列来计算上次使用日期和首次使用日期之间的天数.数据如下:
ID PRODUCT DATE
A ITEM1 1/30/15
B ITEM1 2/23/14
A ITEM2 3/22/15
C ITEM1 1/23/12
B ITEM1 4/12/15
A ITEM3 2/2/14
C ITEM1 1/1/17
A ITEM1 2/20/15
A ITEM1 5/18/15
使用dplyr我可以做
library(dplyr)
library(lubridate)
df <- df %>%
mutate(DATE = mdy(DATE)) %>%
group_by(ID) %>%
filter(PRODUCT == "Item1") %>%
mutate(FIRST = min(DATE), LAST = max(DATE), DAYS = LAST - FIRST)
这给了我
ID PRODUCT DATE FIRST LAST DAYS
(fctr) (fctr) (time) (time) (time) (dfft)
1 A ITEM1 2015-01-30 2015-01-30 2015-05-18 108 days
2 B ITEM1 2014-02-23 2014-02-23 2015-04-12 413 days
3 C ITEM1 2012-01-23 2012-01-23 2017-01-01 1805 days
4 B ITEM1 2015-04-12 2014-02-23 2015-04-12 413 days
5 C ITEM1 2017-01-01 2012-01-23 2017-01-01 1805 days
6 A ITEM1 2015-02-20 2015-01-30 2015-05-18 108 days
7 A ITEM1 2015-05-18 2015-01-30 2015-05-18 108 days
数据:
df <- structure(list(ID = structure(c(1L, 2L, 1L, 3L, 2L, 1L, 3L, 1L, 1L), .Label = c("A", "B", "C"), class = "factor"),
PRODUCT = structure(c(1L, 1L, 2L, 1L, 1L, 3L, 1L, 1L, 1L), .Label = c("ITEM1", "ITEM2", "ITEM3"), class = "factor"),
DATE = structure(c(3L, 6L, 7L, 2L, 8L, 4L, 1L, 5L, 9L),
.Label = c("1/1/17", "1/23/12", "1/30/15", "2/2/14", "2/20/15", "2/23/14", "3/22/15", "4/12/15", "5/18/15"),
class = "factor")),
.Names = c("ID", "PRODUCT", "DATE"), class = "data.frame", row.names = c(NA, -9L))
如何在熊猫中做同样的事情?
解决方法:
使用agg groupby
funcs = dict(FIRST='min', LAST='max', DAYS=np.ptp)
d1 = df.join(df.groupby(['ID', 'PRODUCT']).DATE.agg(funcs), on=['ID', 'PRODUCT'])