【问题标题】:Group by column, calculate number of occurrence of value in another column and divide these numbers按列分组,计算另一列中值的出现次数并将这些数字相除
【发布时间】:2018-11-14 06:51:33
【问题描述】:

我有一个如下所示的 DataFrame:

data = pd.DataFrame({'id' : ['a1', 'a1', 'a1', 'a2','a2','a3','a3','a3'], 
                     'label' : ['0','0','1','0','1','0','1','1']})

我的目标是按 id 分组并进行一些算术运算: 要计算每组中'0'和'1'的出现次数,将每个数字加1000,最后将这些数字除以彼此。例如,对于组“a1”:“0”出现两次,“1”出现一次,然后,2 * 1000 / 1 * 1000 = 2。

所需的 DataFrame 应如下所示:

id number
a1 2
a2 1
a3 0,5

这些 SO 问题对我帮助很大:

Group by two columns and count the occurrences of each combination in pandas

pandas groupby count string occurrence over column

我已经尝试了不同的变体,但仍然没有达到所需的输出。 任何帮助都会非常感激。

【问题讨论】:

    标签: python pandas grouping


    【解决方案1】:

    groupby 然后是value_counts,然后是pct_change

    data.groupby('id').label.apply(lambda x : x.value_counts(sort=False).pct_change()+1).dropna().reset_index(level=0)
    Out[405]: 
       id  label
    0  a1    2.0
    0  a2    1.0
    0  a3    0.5
    

    或者

    pd.crosstab(data.id,data.label).assign(v=lambda x : x['0']/x['1'])
    Out[414]: 
    label  0  1    v
    id              
    a1     2  1  2.0
    a2     1  1  1.0
    a3     1  2  0.5
    

    【讨论】:

      【解决方案2】:
      data.groupby('id').label.apply(lambda x: (x == '0').sum()/(x == '1').sum())
      

      输出:

      id
      a1    2.0
      a2    1.0
      a3    0.5
      Name: label, dtype: float64
      

      【讨论】:

      • 如果组不包含'1',您将获得RuntimeWarning,但将获得np.inf 作为值。
      【解决方案3】:

      您可以使用collections.Counter 并在您的组中不存在1 值的情况下明确定义您需要的结果。

      from collections import Counter
      
      def calculator(x):
          c = Counter(x)
          try:
              return c['0'] / c['1']
          except ZeroDivisionError:
              return np.nan
      
      res = data.groupby('id')['label'].apply(calculator)
      
      id
      a1    2.0
      a2    1.0
      a3    0.5
      Name: label, dtype: float64
      

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 2020-08-21
        • 2019-03-27
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多