【问题标题】:Incremental counter if the value is the same before the point如果该点之前的值相同,则增量计数器
【发布时间】:2022-08-18 17:50:37
【问题描述】:

我在 pandas DataFrame 上有以下 STRING 列。

HOURCENTSEG(string-column)
070026.16169
070026.16169
070026.16169
070026.16169
070052.85555
070052.85555
070109.43620
070202.56430
070202.56431
070202.56434
070202.56434

如您所见,我们有许多元素在该点之前的时间重叠,在所有字段中为避免日期重叠,我必须添加一个增量计数器,如下面的输出示例所示。

HOURCENTSEG (string-column)
070026.00001
070026.00002
070026.00003
070026.00004
070052.00001
070052.00002
070109.00001  (if there is only one value it\'s just 00001)
070202.00001
070202.00002
070202.00003
070202.00004

过去这是一个设计不佳的应用程序,我没有其他选择来解决这个问题。

摘要:在点之后添加一个增量计数器。最大大小为 5,从左边开始填充 0,当点左边的数字相等时。

    标签: python pandas


    【解决方案1】:

    使用GroupBy.cumcount. 拆分值并选择第一个子列表,最后通过Series.str.zfill 添加零:

    s = df['HOURCENTSEG'].str.split('.').str[0]
    df['HOURCENTSEG'] = s + '.' + s.groupby(s).cumcount().add(1).astype(str).str.zfill(5)
    print (df)
         HOURCENTSEG
    0   070026.00001
    1   070026.00002
    2   070026.00003
    3   070026.00004
    4   070052.00001
    5   070052.00002
    6   070109.00001
    7   070202.00001
    8   070202.00002
    9   070202.00003
    10  070202.00004
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      相关资源
      最近更新 更多