I have a pandas dataframe structured in the following way:
num mut
3 -
4 -
5 -
26 -
27 -
30 -
31 -
32 -
I have to extract the rows with consecutive "num" and put them in others df. In this case, I have to obtain three dfs.
First:
num mut
3 -
4 -
5 -
Second:
num mut
26 -
27 -
Third:
num mut
30 -
31 -
32 -
How can I make it?
CodePudding user response:
You can try
m = ~df['num'].diff().fillna(0).le(1)
dfs = [df for _, df in df.groupby(m.cumsum())]
print(dfs)
[ num mut
0 3 -
1 4 -
2 5 -, num mut
3 26 -
4 27 -, num mut
5 30 -
6 31 -
7 32 -]