Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FInd consecutive index pandas

Tags:

python

pandas

I have a dataframe-

cols = ['hops','frequency']
data = [[-13,2],[-8,2],[-5,1],[0,2],[2,1],[4,1],[7,1]]
data = np.asarray(data)
indices = np.arange(0,len(data))

df= pd.DataFrame(data, index=indices, columns=cols)

Now I want to check if the index of the hops related to maximum are consecutive or not. for example here the max freq is 2 and the index having them is 0 1 3.Now we need to check if all the element are consecutive or not.In this case its not as the index have to be 0 1 2 to be consective .

like image 615
ubuntu_noob Avatar asked Aug 30 '25 16:08

ubuntu_noob


1 Answers

Break your logic into parts and you will find constructing a solution easier.

First calculate the indices using Boolean indexing:

idx = df.index[df['frequency'] == df['frequency'].max()]
# Int64Index([0, 1, 3], dtype='int64')

Then calculate the differences between consecutive values:

diffs = np.diff(idx)
# array([1, 2], dtype=int64)

Finally, check if all the differences are equal to 1:

diff_one_check = (diffs == 1).all()
# False
like image 57
jpp Avatar answered Sep 02 '25 04:09

jpp