sashahafner / pystupid

Some notes on Python syntax and more
GNU General Public License v3.0
2 stars 0 forks source link

Create grouping variable for consecutive values #25

Open sashahafner opened 7 months ago

sashahafner commented 7 months ago

This came up while helping Anna on her OAC project. I tried a simple loop, ha!!!!! As if indexing pandas data frames makes that much sense. Anyway, cool solution here:

df = pd.DataFrame({'a': [1, 1, -1, 1, -1, -1]}) print(df) a 0 1 1 1 2 -1 3 1 4 -1 5 -1

print(df['a'].ne(df['a'].shift()).cumsum()) 0 1 1 1 2 2 3 3 4 4 5 4 Name: a, dtype: int32

From https://stackoverflow.com/questions/40802800/how-to-groupby-consecutive-values-in-pandas-dataframe