【问题标题】:Pandas: How to get a row count by the value of a particular column value, and add the count as another column.Pandas:如何通过特定列值的值获取行计数,并将计数添加为另一列。
【发布时间】:2018-06-17 09:30:31
【问题描述】:

假设我的数据看起来像这样,所有数据都按 b 列中的值排序

a   b
1   32
4   32
5   32
9   45
8   45
3   76
5   76
7   76
9   76

让第一行包含特定列值的最有效方法是特定列值出现的总次数。对于具有相同列值的其余行,我希望它们是不同的值(字符串、-1、nan 等,但不是正整数)。在下面的示例中,我使用“-1”作为不同的值

a   b   count b
1   32  3
4   32  -1
5   32  -1
9   45  2
8   45  -1
3   76  4
5   76  -1
7   76  -1
9   76  -1

所以在上表中,b 列为 32 的第一行的“Count b”值为 3,然后列为 32 的其余行的“Count b”值为 -1 .

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    从计算跨度长度开始:

    df = df.merge(df.groupby('b').size().reset_index())
    #   a   b  0
    #0  1  32  3
    #1  4  32  3
    #2  5  32  3
    #3  9  45  2
    #4  8  45  2
    #5  3  76  4
    #6  5  76  4
    #7  7  76  4
    #8  9  76  4
    

    将每个跨度中的重复长度替换为 -1:

    df.loc[df.duplicated(subset=['b',0]), 0] = -1
    
    #   a   b  0
    #0  1  32  3
    #1  4  32 -1
    #2  5  32 -1
    #3  9  45  2
    #4  8  45 -1
    #5  3  76  4
    #6  5  76 -1
    #7  7  76 -1
    #8  9  76 -1
    

    【讨论】:

      【解决方案2】:

      使用groupby.count + pd.Series.duplicated

      df['count_b'] = df.groupby('b').transform('count')
      df.loc[df['b'].duplicated(), 'count_b'] = -1
      
      print(df)
      
         a   b  count_b
      0  1  32        3
      1  4  32       -1
      2  5  32       -1
      3  9  45        2
      4  8  45       -1
      5  3  76        4
      6  5  76       -1
      7  7  76       -1
      8  9  76       -1
      

      如果您愿意,可以将这两个步骤与numpy.where 结合起来:

      import numpy as np
      
      df['count_b'] = np.where(df['b'].duplicated(), -1,
                               df.groupby('b')['b'].transform(len))
      

      【讨论】:

        【解决方案3】:

        value_countfillna 一起使用

        df['New']=df.b.drop_duplicates().map(df.b.value_counts())
        df.New.fillna(-1,inplace=True)
        df.New=df.New.astype(int)
        df
        Out[197]: 
           a   b  New
        0  1  32    3
        1  4  32   -1
        2  5  32   -1
        3  9  45    2
        4  8  45   -1
        5  3  76    4
        6  5  76   -1
        7  7  76   -1
        8  9  76   -1
        

        【讨论】:

          猜你喜欢
          • 2022-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-10
          • 2020-08-28
          • 1970-01-01
          • 1970-01-01
          • 2021-12-22
          相关资源
          最近更新 更多