代码之家  ›  专栏  ›  技术社区  ›  Chris Macaluso

Python比较和计算行值

  •  0
  • Chris Macaluso  · 技术社区  · 7 年前

    我想逐行比较两列,并在每行中的特定值不正确时计数。例如:

    group       landing_page 
    control     new_page
    control     old_page
    treatment   new_page
    treatment   old_page
    control     old_page
    

    我想数数次数 treatment new_page control old_page . 我想也可能是相反的,又名 新建\u页 .

    3 回复  |  直到 7 年前
        1
  •  1
  •   b2002    7 年前

    使用groupby查找组/登录页对的计数。

    再次使用groupby查找组计数。 要查找每个组中其他登录页的计数,请减去每个

    df = pd.DataFrame({'group': ['control', 'control', 'treatment',
                                 'treatment', 'control'],
                       'landing_page': ['new_page', 'old_page', 'new_page',
                                        'old_page', 'old_page']})
    
    # find counts per pairing
    df_out = df.groupby(['group', 'landing_page'])['landing_page'].count().to_frame() \
        .rename(columns={'landing_page': 'count'}).reset_index()
    # find totals for groups
    df_out['grp_total'] = df_out.groupby('group')['count'].transform('sum')
    # find count not equal to landing page
    df_out['inverse_count'] = df_out['grp_total'] - df_out['count']
    
    print(df_out)
    
           group landing_page  count  grp_total  inverse_count
    0    control     new_page      1          3              2
    1    control     old_page      2          3              1
    2  treatment     new_page      1          2              1
    3  treatment     old_page      1          2              1
    
        2
  •  0
  •   CJ Barcelos    7 年前

    这听起来像是一份适合年轻人的工作 zip() 功能。

    group = ["control", "control", "treatment", "treatment", "control"]
    landingPage = ["new_page", "old_page", "new_page", "old_page", "old_page"]
    
    treatmentNotNew = 0
    controlNotOld = 0
    

    然后将要比较的两个输入压缩为元组迭代器:

    zipped = zip(group, landingPage)
    

    现在您可以迭代元组值a(group)和b(landing apge),同时每次计算 treatment != new_page control != old_page :

    for a, b in zipped:
        if((a == "treatment") and (not b == "new_page")):
            treatmentNotNew += 1
    
        if((a == "control") and (not b == "old_page")):
            controlNotOld += 1
    

    print("treatmentNotNew = " + str(treatmentNotNew))
    print("controlNotOld = " + str(controlNotOld))
    
    >> treatmentNotNew = 1
    >> controlNotOld = 1
    
        3
  •  0
  •   PReidy    7 年前

    我会用 map

    df = pd.DataFrame({
        'group': ['control', 'control', 'treatment', 'treatment', 'control'],
        'landing_page': ['old_page', 'old_page', 'new_page', 'old_page', 'new_page']
    })
    
    df['mapping'] = df.group.map({'control': 'old_page', 'treatment': 'new_page'})
    
    (df['landing_page'] != df['mapping']).sum()
    # 2