在Python Pandas中执行groupby和聚合

2024-04-29 13:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧看起来像

user    time15min             name                  is_purchase
A       2015-08-18 16:45:00   Words With Friends    0
A       2015-08-18 16:45:00   Clash of Clans        0
A       2015-08-18 16:45:00   Words With Friends    0
A       2015-08-18 16:45:00   Clash of Clans        1
A       2015-08-18 17:00:00   Sudoku                0
B       2015-08-18 17:00:00   Angry Birds           0
B       2015-08-18 17:00:00   Candy Crush           0
B       2015-08-18 17:00:00   Candy Crush           0
....

time15min列包含用户在手机中玩游戏的15分钟时间段。在

我需要做的是创建一个聚合的数据帧,每个用户和每个时间段15分钟,有一个列显示哪个游戏玩得最多,以及在这段时间内是否有任何应用内购买。在

所以,结果是

^{pr2}$

如果a的第一个例子中出现平局,我们可以只取第一个字母顺序的(本例中是部族冲突)。在


Tags: of数据用户nameiswithwordsclans
1条回答
网友
1楼 · 发布于 2024-04-29 13:51:31

您可以从here应用配方

import pandas as pd
## read in your data from clipboard and get the columns right
df = pd.read_clipboard(sep='\s{2,}')

df.loc[:,'time15min'] = pd.to_datetime(df['time15min'])

## set the index to time15min, so df2 has a DateTimeIndex
df2 = df.set_index('time15min')

## Use .agg to count the names and total the purchases
df3=df2.groupby(['user',pd.TimeGrouper('15min'),'name']).agg({
                           'name':'count','is_purchase':'sum'})

## Create a mask to find the max for each group
mask = df3.groupby(level=[0,1]).agg('idxmax')
df3_count = df3.loc[mask['name']]

df3_count

结果如下:

^{pr2}$

相关问题 更多 >