繁体   English   中英

添加列,保留按 pandas 中的变量分组的不同值的计数

[英]Add column that keeps count of distinct values grouped by a variable in pandas

我有一个名为df的 pandas dataframe 看起来像这样

name   test_type   block  
joe    0           1                
joe    0           1            
joe    1           2            
joe    1           2            
joe    0           3            
joe    0           3            
jim    1           1            
jim    1           1            
jim    0           2            
jim    0           2           
jim    1           3            
jim    1           3           

我想添加一个列来跟踪每次我为name下的每个人获得block的新值,但除以test_type

这是我需要的:

name   test_type   block   block_by_test_type
joe    0           1       1         
joe    0           1       1     
joe    1           2       1     
joe    1           2       1     
joe    0           3       2     
joe    0           3       2     
jim    1           1       1     
jim    1           1       1     
jim    0           2       1     
jim    0           2       1     
jim    1           3       2     
jim    1           3       2    

我一直在使用groupbycumsum ,但我无法得到我需要的东西。

提前致谢。

看起来您与groupbycumsum duplicated使这一切融合在一起。

df['block_by_test_type'] = (
    df.groupby(['name','test_type'], as_index=False)
        .apply(lambda x: (~x['block'].duplicated()).cumsum()).droplevel(0)
)

print(df)

结果

   name  test_type  block  block_by_test_type
0   joe          0      1                   1
1   joe          0      1                   1
2   joe          1      2                   1
3   joe          1      2                   1
4   joe          0      3                   2
5   joe          0      3                   2
6   jim          1      1                   1
7   jim          1      1                   1
8   jim          0      2                   1
9   jim          0      2                   1
10  jim          1      3                   2
11  jim          1      3                   2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM