为连续的一组创建连续的事件ID

问题描述 投票:1回答:1

我有这样的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'。因此,在新列中,基于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个回答
0
投票

这将完成工作:

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,也可以使用其他方法)。

© www.soinside.com 2019 - 2024. All rights reserved.