Find index where elements change value pandas dataframe

Question:

Regaring to this question/answer, is there a way to accomplish the same function for a pandas dataframe structure without casting it as a numpy array?

Asked By: ntmt

||

Answers:

Update: we can use this per @LorenzoMeneghetti

s[s.diff() != 0].index.tolist()

Output:

[0, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16]

s = pd.Series([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5])

print(s.diff()[s.diff() != 0].index.values)

OR:

df = pd.DataFrame([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5])

print(df[0].diff()[df[0].diff() != 0].index.values)

Output:

[ 0  5  8  9 10 11 12 13 14 15 16]
Answered By: Scott Boston
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.