Pandas:找到在列中重复模式并将其作为循环分组

2024-06-16 14:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列,值为'loading'、'loading'、'nan'。我想按顺序查找“加载”和“卸载”的模式,并将相应的行标记为cycle1、cycle2,依此类推。在

enter image description here

pic显示了一个这样的序列,其中'loading'和'loading'我希望一个新列的所有行的值都为'1',下一个'loading'和'loading'的序列为'2',以此类推。在

我没有逻辑告诉你,但如果你能帮助我,我将不胜感激。下图显示了我的期望

enter image description here


Tags: 标记顺序模式序列逻辑nanpiccycle2
1条回答
网友
1楼 · 发布于 2024-06-16 14:45:16

下面是一个基于循环的方法。如果有人能更好地利用熊猫,我会很兴奋的。在

import pandas as pd

data = {'Event': ['Start','Going','Stop','Start','Stop','Start','Start','Going','Going','Going','Stop','Stop','Start','Stop']}


df = pd.DataFrame(data)

cycle = 0            
new_cycle = True
cycles = []
for x in df.Event:
    if new_cycle and x == 'Start':
        new_cycle = False
        cycle += 1
    elif x == 'Stop':
        new_cycle = True
    cycles.append(cycle)

df['cycles'] = cycles
print(df)

输出

^{pr2}$

相关问题 更多 >