简体   繁体   中英

Get index of row where column value changes from previous row

I have a pandas dataframe with a column such as :

df1 = pd.DataFrame({ 'val': [997.95, 997.97, 989.17, 999.72, 984.66, 1902.15]})

I have 2 types of events that can be detected from this column, I wanna label them 1 and 2 .

I need to get the indexes of each label , and to do so I need to find where the 'val' column has changed a lot (± 7 ) from previous row.

Expected output:

one = [0, 1, 3, 5]
two = [2, 4 ]

Use Series.diff with mask for test less values like 0 , last use boolean indexing with indices:

m = df1.val.diff().lt(0)
#if need test less like -7
#m = df1.val.diff().lt(-7)
one = df1.index[~m]
two = df1.index[m]
print (one)
Int64Index([0, 1, 3, 5], dtype='int64')

print (two)
nt64Index([2, 4], dtype='int64')

If need lists:

one = df1.index[~m].tolist()
two = df1.index[m].tolist()

Details :

print (df1.val.diff())

0       NaN
1      0.02
2     -8.80
3     10.55
4    -15.06
5    917.49
Name: val, dtype: float64

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