Skip to content

Instantly share code, notes, and snippets.

@alimanfoo
Created November 5, 2017 23:53
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alimanfoo/c5977e87111abe8127453b21204c1065 to your computer and use it in GitHub Desktop.
Save alimanfoo/c5977e87111abe8127453b21204c1065 to your computer and use it in GitHub Desktop.
Find runs of consecutive items in a numpy array.
import numpy as np
def find_runs(x):
"""Find runs of consecutive items in an array."""
# ensure array
x = np.asanyarray(x)
if x.ndim != 1:
raise ValueError('only 1D array supported')
n = x.shape[0]
# handle empty array
if n == 0:
return np.array([]), np.array([]), np.array([])
else:
# find run starts
loc_run_start = np.empty(n, dtype=bool)
loc_run_start[0] = True
np.not_equal(x[:-1], x[1:], out=loc_run_start[1:])
run_starts = np.nonzero(loc_run_start)[0]
# find run values
run_values = x[loc_run_start]
# find run lengths
run_lengths = np.diff(np.append(run_starts, n))
return run_values, run_starts, run_lengths
@endrebak
Copy link

Beautiful work. I used this in my pyrle library. You are given credit in the source code and changelog :)

@bmeyers
Copy link

bmeyers commented Feb 6, 2020

This is great! Just what I needed, thank you. Included in my research code with attribution.

@alimanfoo
Copy link
Author

Glad it's useful!

@endrebak
Copy link

endrebak commented Feb 7, 2020

Btw, if anyone needs an artihmetic RLE library, check out https://github.com/pyranges/pyrle :)

@alimanfoo
Copy link
Author

Btw, if anyone needs an artihmetic RLE library, check out https://github.com/pyranges/pyrle :)

👍

@MelikbekyanAshot
Copy link

Thank you :)

@Maghoumi
Copy link

Thanks! This is exactly what I needed!

@jerrylususu
Copy link

Thanks! Nice work, just what I want!

@ivoolong
Copy link

ivoolong commented Jun 8, 2021

膜拜大佬

@rbpiccinini
Copy link

Very good! Thanks.

@Karlheinzniebuhr
Copy link

Thanks finally a solution that works as intended

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment