Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice pandas dataframe in groups of consecutive values

I have a dataframe containing sections of consecutive values that eventually "skip" (that is, are increased by more than 1). I would like to split the dataframe, similar to groupby function (alphabetic indexing just for show):

    A
a   1
b   2
c   3
d   6
e   7
f   8
g   11
h   12
i   13

# would return

a   1
b   2
c   3
-----
d   6
e   7
f   8
-----
g   11
h   12
i   13
like image 729
heltonbiker Avatar asked Sep 30 '14 13:09

heltonbiker


2 Answers

Slightly improved for speed answer...

for k,g in df.groupby(df['A'] - np.arange(df.shape[0])):
    print g
like image 172
ZJS Avatar answered Oct 07 '22 20:10

ZJS


My two cents just for the fun of it.

In [15]:

for grp, val in df.groupby((df.diff()-1).fillna(0).cumsum().A):
    print val
   A
a  1
b  2
c  3
   A
d  6
e  7
f  8
    A
g  11
h  12
i  13
like image 35
CT Zhu Avatar answered Oct 07 '22 20:10

CT Zhu