【问题标题】:Most viewed product浏览次数最多的产品
【发布时间】:2021-09-15 03:17:27
【问题描述】:

我正在尝试根据用户 ID 查找浏览次数最多的产品。如果两个产品的浏览次数相同,则选择最近浏览的产品。

我有以下编码:

#tabulating most viewed product by an user in the last 15 days
df_most_viewed_product= new_df.groupby('UserID')['ProductID'].apply(lambda x: x.value_counts().index[0]).reset_index()

它会为所有 USER ID 查找查看次数最多的产品,除了那些 USER 在相同时间查看两个产品的产品。在这种情况下,我需要将输出作为最近查看的产品。

        ProductID   UserID  Activity    OS      date        time
392281  Pr102405    U100040 PAGELOAD    Windows 2018-05-21  04:18:05.465000
764999  Pr102405    U100040 CLICK   Windows 2018-05-23  15:52:02.061000
1501633 Pr105055    U100040 PAGELOAD    Windows 2018-05-23  15:52:39.035000
1603959 Pr100283    U100040 PAGELOAD    Windows 2018-05-25  15:27:37.062000
2212636 Pr100513    U100040 PAGELOAD    Windows 2018-05-27  02:18:47.676000
3093767 Pr100513    U100040 PAGELOAD    Windows 2018-05-26  20:47:49.788000

答案应该是Pr100513,因为它最近被查看过。

【问题讨论】:

    标签: pandas dataframe time group-by


    【解决方案1】:

    按照您的描述系统地构建它

    • 根据 UserIDProductID 获取点击次数和最后点击次数
    • 从此聚合数据框中选择与 max hits 和 max last_hit 匹配的行
    import io
    import pandas as pd
    df = pd.read_csv(io.StringIO(''' ProductID UserID Activity OS date time 
    392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000 
    764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000 
    1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000 
    1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000 
    2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000 
    3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000 '''), sep="\s", engine="python")
    
    df["date"] = pd.to_datetime(df["date"] + " " + df["time"])
    
    # count hits per user and product after sorting so last_hit works
    dfh = df.sort_values(["UserID","date"]).groupby(["UserID","ProductID"]).agg(hits=("OS","size"),last_hit=("date","last"))
    # select the row with max hits and last hit
    dfh.loc[dfh["hits"].eq(dfh["hits"].max()) & dfh["last_hit"].eq(dfh["last_hit"].max())]
    
    

    输出

                       hits                last_hit
    UserID  ProductID                              
    U100040 Pr100513      2 2018-05-27 02:18:47.676
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多