【问题标题】:Pandas: add column with progressive count of elements meeting a conditionPandas:添加满足条件的元素的累进计数列
【发布时间】:2019-01-17 00:47:18
【问题描述】:

给定以下数据框df:

df = pd.DataFrame({'A':['Tony', 'Mike', 'Jen', 'Anna'], 'B': ['no', 'yes', 'no', 'yes']})

    A    B
0   Tony no 
1   Mike yes
2   Jen  no
3   Anna yes

我想添加另一列,逐步计算带有df['B']='yes' 的元素:

    A    B   C
0   Tony no  0
1   Mike yes 1
2   Jen  no  0
3   Anna yes 2

我该怎么做?

【问题讨论】:

    标签: python pandas conditional-statements pandas-groupby


    【解决方案1】:

    您可以将numpy.where 与布尔掩码的cumsum 一起使用:

    m = df['B']=='yes'
    df['C'] = np.where(m, m.cumsum(), 0)
    

    另一种解决方案是通过过滤创建count布尔掩码,然后通过reindex添加0值:

    m = df['B']=='yes'
    df['C'] = m[m].cumsum().reindex(df.index, fill_value=0)
    print (df)
          A    B  C
    0  Tony   no  0
    1  Mike  yes  1
    2   Jen   no  0
    3  Anna  yes  2
    

    性能(实际数据应该不同,最好先检查一下):

    np.random.seed(123)
    N = 10000
    L = ['yes','no']
    df = pd.DataFrame({'B': np.random.choice(L, N)})
    print (df)
    
    In [150]: %%timeit
         ...: m = df['B']=='yes'
         ...: df['C'] = np.where(m, m.cumsum(), 0)
         ...: 
    1.57 ms ± 34.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [151]: %%timeit
         ...: m = df['B']=='yes'
         ...: df['C'] = m[m].cumsum().reindex(df.index, fill_value=0)
         ...: 
    2.53 ms ± 54.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
    In [152]: %%timeit
         ...: df['C'] = df.groupby('B').cumcount() + 1
         ...: df['C'].where(df['B'] == 'yes', 0, inplace=True)
    
    4.49 ms ± 27.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    【讨论】:

      【解决方案2】:

      您可以使用GroupBy + cumcount 后跟pd.Series.where:

      df['C'] = df.groupby('B').cumcount() + 1
      df['C'].where(df['B'] == 'yes', 0, inplace=True)
      
      print(df)
      
            A    B  C
      0  Tony   no  0
      1  Mike  yes  1
      2   Jen   no  0
      3  Anna  yes  2
      

      【讨论】:

      • 很好的答案,因为即使您尝试使用非二进制列解决相同的问题,它也可以工作
      猜你喜欢
      • 2021-10-28
      • 1970-01-01
      • 2018-07-26
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多