【问题标题】:Determining the number of unique entry's left after experiencing a specific item in pandas确定在熊猫中体验特定项目后剩余的唯一条目数
【发布时间】:2018-02-03 20:48:57
【问题描述】:

我有一个包含三列 timestamplecture_iduserid 的数据框

我正在尝试编写一个循环来计算在体验特定讲座后放弃(再也没有见过)的学生人数。目标是最终有第四列,显示在听完特定讲座后剩余的学生人数。

我在用 python 写这个时遇到了麻烦,我尝试了一个从未完成的 for 循环(我有 13m 行)。

import pandas as pd
import numpy as np


ids = list(np.random.randint(0,5,size=(100, 1)))
users = list(np.random.randint(0,10,size=(100, 1)))
dates = list(pd.date_range('20130101',periods=100, freq = 'H'))


dft = pd.DataFrame(
    {'lecture_id': ids,
     'userid': users,
     'timestamp': dates
    })

我想制作一个新的数据框,向每个参加过 x 讲座的用户显示,有多少人再也没有回来(丢弃)。

【问题讨论】:

    标签: python-3.x pandas time-series


    【解决方案1】:

    不确定这是否是您想要的,也不确定这是否可以更简单,但这可能是一种方法:

    import pandas as pd
    import numpy as np
    
    np.random.seed(42)
    
    ids = list(np.random.randint(0,5,size=(100, 1)[0]))
    users = list(np.random.randint(0,10,size=(100, 1)[0]))
    dates = list(pd.date_range('20130101',periods=100, freq = 'H'))
    df = pd.DataFrame({'lecture_id': ids, 'userid': users, 'timestamp': dates})
    
    # Get the last date for each user
    last_seen = df.timestamp.iloc[df.groupby('userid').timestamp.apply(lambda x: np.argmax(x))]
    
    df['remaining'] = len(df.userid.unique())
    
    tmp = np.zeros(len(df))
    tmp[last_seen.index] = 1
    df['remaining'] = (df['remaining']- tmp.cumsum()).astype(int)
    
    df[-10:]
    

    最后 10 个条目在哪里:

        lecture_id           timestamp  userid  remaining
    90           2 2013-01-04 18:00:00       9          6
    91           0 2013-01-04 19:00:00       5          6
    92           2 2013-01-04 20:00:00       6          6
    93           2 2013-01-04 21:00:00       3          5
    94           0 2013-01-04 22:00:00       6          4
    95           2 2013-01-04 23:00:00       7          4
    96           4 2013-01-05 00:00:00       0          3
    97           1 2013-01-05 01:00:00       5          2
    98           1 2013-01-05 02:00:00       7          1
    99           0 2013-01-05 03:00:00       4          0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-10
      • 2018-12-27
      • 1970-01-01
      • 2018-04-25
      • 2019-07-20
      • 2022-11-26
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多