gpt4 book ai didi

python - 按随机事件对数据帧进行分组,并使用组计数设置一个新列

转载 作者:行者123 更新时间:2023-11-30 22:43:43 25 4
gpt4 key购买 nike

我一直在努力尝试对数据集进行分类;也许有人可以帮助我或指出正确的方向。

我有一个数据框,其中包含一系列相继发生的事件,并且在某个随机点,一个事件被注册在其中一列中。它看起来像这样:

       Timestamp         Event
0 10/26/2015 22:50:15 0
1 10/26/2015 22:50:46 0
2 10/26/2015 22:50:50 0
3 10/26/2015 22:50:51 0
4 10/26/2015 22:51:15 1
5 10/26/2015 22:51:47 0
6 10/26/2015 22:52:38 0
7 10/26/2015 22:54:46 1
8 10/26/2015 22:55:46 0

我需要创建一个新列,用于标识在每次出现或事件“1”之前出现的每组记录。并在该组中设置一个计数器。结果应该是这样的:

       Timestamp         Event   Group
0 10/26/2015 22:50:15 0 1
1 10/26/2015 22:50:46 0 1
2 10/26/2015 22:50:50 0 1
3 10/26/2015 22:50:51 0 1
4 10/26/2015 22:51:15 1 1
5 10/26/2015 22:51:47 0 2
6 10/26/2015 22:52:38 0 2
7 10/26/2015 22:54:46 1 2

请注意,现在导致“1”事件的记录在结果中将被忽略。

最佳答案

您可以在 Event 列上使用 cumsum(),只要遇到 1 就会给出新的组 ID。与 shift() 结合使用,您将能够按预期创建 Group 列:

df['Group'] = df.Event.shift().cumsum().fillna(0) + 1

df.loc[df.index <= df.Event.iloc[::-1].idxmax()]
# to filter trailing zero records

enter image description here

<小时/>

另一种选择:

g = df.Event.iloc[::-1].cumsum()
df.loc[g != 0, 'Group'] = g.max() - g + 1
df.dropna()

关于python - 按随机事件对数据帧进行分组,并使用组计数设置一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com