【问题标题】:Python: Percent of Applications/Any record to their User AnalysisPython:应用程序的百分比/对其用户分析的任何记录
【发布时间】:2019-08-13 17:04:13
【问题描述】:

大家下午好,我在下面有一个数据框。

UserId  Application
    1       apple
    1       orange
    1       apple
    1       pear
    2       apple
    2       orange
    2       pear
    2       grapefruit
    3       apple
    3       grapefruit
    3       apple
    1       apple

我正在尝试创建一个列表,将每个唯一应用程序计算到拥有它们的用户 ID 的百分比。作为输出的示例,下表如下所示

Application    Percentage
apple              100
orange             66
pear               66 
grapefruit         66

这个输出告诉我,对于每个用户,苹果出现 100% 的时间橙色出现在 66% 的时间。等等等等,但不知何故我无法让它工作。

我下面的代码可以工作,但会产生 3.0 作为值。

dfsearch['Percentage'] = (len(dfsearch.Application.value_counts())/len(dfsearch.UserID.value_counts()))
dfsearch

这可能是不正确的,因为它不是一个列表,但这就是我需要帮助的原因:)

【问题讨论】:

    标签: python pandas numpy statistics analysis


    【解决方案1】:

    你可以先用drop_duplicates删除重复记录,然后调用value_counts,除以唯一用户数再乘以100:

    x = df.drop_duplicates()['Application'].value_counts() / len(df['UserId'].unique()) * 100
    x
    

    输出:

    apple         100.000000
    pear           66.666667
    grapefruit     66.666667
    orange         66.666667
    Name: Application, dtype: float64
    

    然后将其转换为DataFrame:

    x.astype(int).to_frame('Percentage').rename_axis('Application').reset_index()
    

    输出:

      Application  Percentage
    0       apple         100
    1        pear          66
    2  grapefruit          66
    3      orange          66
    

    【讨论】:

      【解决方案2】:

      使用groupby() + nunique():

      dfsearch.groupby("Application").UserID.nunique()/dfsearch.UserID.nunique()
      #Application
      #apple         1.000000
      #grapefruit    0.666667
      #orange        0.666667
      #pear          0.666667
      #Name: UserId, dtype: float64
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-31
        • 2011-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多