Skip to content

Instantly share code, notes, and snippets.

@bathtimefish
Last active January 8, 2019 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bathtimefish/1db3fe80b6db1b865c669ffcdf2a2a21 to your computer and use it in GitHub Desktop.
Save bathtimefish/1db3fe80b6db1b865c669ffcdf2a2a21 to your computer and use it in GitHub Desktop.
配列からスライス窓を生成する
import numpy as np
def getSlidingWindow(a, size, step=1):
if not ((type(size) == type(0)) and (type(step) == type(0))):
raise Exception("type(size) and type(step) must be int.")
if step > size:
raise Exception("step must not be larger than size.")
if size > len(a):
raise Exception("size must not be larger than array length.")
a = np.asarray(a)
h = ((len(a)-size)/step)+1
indexer = np.arange(size)[None, :] + step*np.arange(int(h))[:, None]
window = a[indexer]
return window
a = list(range(10,30))
print(getSlidingWindow(a, 10, 2))
# -> array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
# [12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
# [14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
# [16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
# [18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
# [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment