首页 文章

用groupby按条件求和pandas列

提问于
浏览
1

我有大数据框,我需要在'view_day'列中为'for'时段加上'view'列 . 数据框看起来像:

size = 400
dtype = [('view_day', 'int32'), ('account', 'int32'), ('view', 'int32')]
values = np.ones(size, dtype=dtype)

dfo = pd.DataFrame(values)

dfo['view_day'] = np.random.randint(7605, 7605 + 180, dfo.shape[0])
dfo['account'] = np.random.randint(1548051, 1548051 + 10, dfo.shape[0])
dfo['view'] = np.random.randint(600, 1800, dfo.shape[0])
    view_day account        view
0   7651     1548055        1338
1   7698     1548054        1147

我需要创建新的数据框,帐户作为索引,并总结过去30天的总视图 . 新数据框架如下所示:

accounts= dfo.account.unique()

size = len(accounts)
dtype = [('view_last_30', 'int32')]
values = np.zeros(size, dtype=dtype)
index = accounts
dfc1 = pd.DataFrame(values, index=index)
           view_last_30
1548058    sum of view of this account for the last 30 days
1548057             "

我设法通过以下方式对groupby进行分组和汇总:

last_day= dfo['view_day'].max()
dfo['last_30'] = dfo['view_day'] > last_day- 30
gl = dfo.groupby(['account', 'last_30'])['view']
h = gl.sum()

我明白了:

account  last_30
1548051  False      30439
         True        6713
1548052  False      27491
         True        8477

如何将last_30 == True的总和复制到新创建的数据框中?所以我会得到:

view_last_30
1548051    6713
1548052    8477

2 回答

  • 2

    get_level_values 然后使用布尔选择

    df.loc[df.index.get_level_values('last_30').values].\
           reset_index('last_30',drop=True)
    Out[590]: 
             value
    account       
    1548051   6713
    1548052   8477
    
  • 2

    你可以使用IndexSlice accessor:

    In [57]: s
    Out[57]:
    account  last_30
    1548051  False      30439
             True        6713
    1548052  False      27491
             True        8477
    Name: val, dtype: int64
    
    In [58]: s.loc[pd.IndexSlice[:,True]]
    Out[58]:
    account
    1548051    6713
    1548052    8477
    Name: val, dtype: int64
    

相关问题