Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

python - Pandas:Find the repeating patterns in a column and group them as cycles

I've a column with values 'loading', 'unloading','nan'. I want to look for the pattern of 'loading' and 'unloading' in that order and mark those corresponding rows as cycle1, cycle2 so on.

enter image description here

The pic shows one such sequence where 'loading' and 'unloading' and I want a new column to have the values of '1' for all those rows and the next sequence of 'loading' and 'unloading' as '2' so on.

I've got no logic to show you but would appreciate if you can help me. The below pic shows what I expect

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a loop based way to do it. I'd be excited if someone else has a way that better makes use of pandas.

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)

Output

    Event  cycles
0   Start       1
1   Going       1
2    Stop       1
3   Start       2
4    Stop       2
5   Start       3
6   Start       3
7   Going       3
8   Going       3
9   Going       3
10   Stop       3
11   Stop       3
12  Start       4
13   Stop       4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...