【问题标题】:How can I calculate the percentage of given binary variables between groups in a dataframe如何计算数据框中组之间给定二进制变量的百分比
【发布时间】:2021-04-10 13:20:00
【问题描述】:

我有一个多人回答多个问题的数据框。问题被操作化为 1 = 同意和 0 = 不同意。同一个人回答了多个问题,现在我想找出同意声明的百分比,因此是 1,与答案的总数相比。 数据框的组织方式是每个问题有一行。每个人回答 8 个问题,所以我们为每个人准备了 8 行。我想计算每个人的“同意”(或 1 个)陈述与每个人回答的问题总数相比的百分比(因此为 8 个)。

【问题讨论】:

    标签: dataframe percentage


    【解决方案1】:
    # display how the targets are distributed
    def configure_target_statistic(targets):
        trg_cnt = targets.value_counts()
        labels, sizes = (np.array(trg_cnt.index)), (np.array(100*(trg_cnt/trg_cnt.sum())))
        py.iplot(go.Figure(data=[go.Pie(labels=labels, values=sizes)], layout=go.Layout(title='Target Distribution',font=dict(size=15),width=500, height=500)))
        return trg_cnt
    
    configure_target_statistic(df['answers'])
    

    你只需要导入,这就足够了:

    import numpy as np
    import pandas as pd
    import plotly.offline as py
    import plotly.graph_objs as go
    

    【讨论】:

      【解决方案2】:

      假设您的数据框有两列 user_id 和 question_id,您可以通过它们识别每一行,这是一个简单的解决方案:

      import pandas as pd    
      df=pd.DataFrame([[1,6,1],[1,7,1],[2,6, 1],[2,7, 0]],columns=  ['user_id','question_id','agree'])
      grp=df.groupby(['user_id'])['agree']
      print(100*grp.sum()/grp.count())
      

      在代码中(最后一行),我只考虑用户尝试计算百分比的问题数。

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 2021-12-11
        • 2021-10-15
        • 2013-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多