Created
September 16, 2019 12:16
-
-
Save gottadiveintopython/cb4058e5ebc468c30847f05cf4b37810 to your computer and use it in GitHub Desktop.
inverse numpy's bincount()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import itertools | |
| from timeit import timeit | |
| arr = np.random.randint(3, size=100, dtype='uint8') | |
| def method_me(arr): | |
| return np.array( | |
| tuple(itertools.chain.from_iterable( | |
| itertools.repeat(index, value) | |
| for index, value in enumerate(arr) | |
| )), | |
| dtype=np.uint8 | |
| ) | |
| def method_hayataka(arr): | |
| return np.repeat(np.arange(arr.size), arr) | |
| def method_eelco(arr): | |
| p = np.cumsum(arr) | |
| i = np.zeros(p[-1], np.uint8) | |
| np.add.at(i, p[:-1], 1) | |
| return np.cumsum(i) | |
| print('me:', timeit(lambda: method_me(arr), number=2000)) | |
| print('hayataka:', timeit(lambda: method_hayataka(arr), number=2000)) | |
| print('eelco:', timeit(lambda: method_eelco(arr), number=2000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment