【问题标题】:How to iterate each record in a group如何迭代组中的每条记录
【发布时间】:2017-07-19 12:27:46
【问题描述】:

我想添加一个迭代组值的列。数据框已根据需要预先排序:

Index :|: GRP BY Col :|: New Col:|  
0     :|: 1          :|: 0      :|
1     :|: 1          :|: 1      :|   
2     :|: 1          :|: 2      :|   
3     :|: 2          :|: 0      :|   
4     :|: 2          :|: 1      :|    

【问题讨论】:

    标签: python python-3.x pandas group-by counter


    【解决方案1】:

    我觉得你需要cumcount:

    df = pd.DataFrame({'GRP BY Col':[1,1,1,2,2]})
    df['New Col'] = df.groupby('GRP BY Col').cumcount()
    print (df)
       GRP BY Col  New Col
    0           1        0
    1           1        1
    2           1        2
    3           2        0
    4           2        1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-09
      • 2015-03-21
      • 2021-02-11
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多