How to detect constant absolute delta in integer series?

How to detect constant absolute delta in integer series?



I have integer series as follows:


data1 = [1, 2, 3, 4, 3, 2, 1, 2, 1, 1]

data2 = [4, 0, 0, 0, 8, 0, 0, 0]



We can see data1 seems to be "continuous" while data2 is not, as data1 has a maximum constant absolute delta of 1.


data1


data2


data1



How can I decide using Pandas that data1 is "continuous", and data2 is not?


data1




2 Answers
2



Define continuous to mean "consecutive differences are at most 1 in absolute value". To detect this, you can use .diff():


.diff()


In [1]: series1, series2 = pd.Series(data1), pd.Series(data2)

In [2]: series1.diff().fillna(0).abs().max()
Out[2]: 1.0

In [3]: series2.diff().fillna(0).abs().max()
Out[3]: 8.0



So series1.diff().fillna(0).abs().max() <= 1 will evaluate to True, and series2.diff().fillna(0).abs().max() <= 1 will evaluate to False.


series1.diff().fillna(0).abs().max() <= 1


True


series2.diff().fillna(0).abs().max() <= 1


False



Similar to Andrey's solution but this takes advantage of pandas' rolling windows series method.


data1.rolling(2).apply(lambda x: abs(np.diff(x)) <= 1).all()
>>> True

data2.rolling(2).apply(lambda x: abs(np.diff(x)) <= 1).all()
>>> False



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.