简体   繁体   中英

FInd consecutive index 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM