【问题标题】:Create sequential event id for groups of consecutive ones为连续事件组创建顺序事件 id
【发布时间】:2020-04-24 13:46:21
【问题描述】:

我有一个像这样的 df:

Period  Count
1       1
2       0
3       1
4       1
5       0
6       0
7       1
8       1
9       1
10      0

如果 Count 中有两次或多次连续出现 1,我想在新列中返回“事件 ID”,如果没有,则返回 0。因此,在新列中,根据列 Count 中满足的此条件,每一行都会得到 1。我想要的输出是:

Period  Count  Event_ID
1       1      0
2       0      0
3       1      1
4       1      1
5       0      0
6       0      0
7       1      2
8       1      2
9       1      2
10      0      0

我已经研究并找到了解决方案,可以让我标记出连续的相似数字组(例如 1),但我还没有遇到我需要的东西。我希望能够使用这种方法来计算任意数量的连续出现,而不仅仅是 2。例如,有时我需要连续出现 10 次,我这里的示例中只使用 2。

【问题讨论】:

    标签: python python-3.x pandas iteration


    【解决方案1】:

    这样就可以了:

    ones = df.groupby('Count').groups[1].tolist()
    # creates a list of the indices with a '1': [0, 2, 3, 6, 7, 8]
    event_id = [0] * len(df.index)
    # creates a list of length 10 for Event_ID with all '0'
    
    # find consecutive numbers in the list of ones (yields [2,3] and [6,7,8]):
    for k, g in itertools.groupby(enumerate(ones), lambda ix : ix[0] - ix[1]):
      sublist = list(map(operator.itemgetter(1), g))
      if len(sublist) > 1:
        for i in sublist:
          event_id[i] = len(sublist)-1    
    # event_id is now [0, 0, 1, 1, 0, 0, 2, 2, 2, 0]   
    
    df['Event_ID'] = event_id
    

    for 循环改编自this example(使用itertools,也可以使用其他方法)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 2014-12-08
      相关资源
      最近更新 更多