8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのlistをslideしながらwindow幅で切り出す

Last updated at Posted at 2019-07-20

タイトルが雑でごめんなさい。

以下のようにPythonのリストをslide幅でずらしながらwindow幅で切り出す方法です。
リストをwindow幅でslideずつずらす.png
機械学習などでよく使う割に忘れやすいのでメモしておきます。

実装

>>> s = 3 #slide
>>> w = 5 #window

>>> array = list(range(10))
>>> [array[i:i+w] for i in range(0,len(array)-w+s,s)]
[[0, 1, 2, 3, 4], [3, 4, 5, 6, 7], [6, 7, 8, 9]]

>>> array = list(range(11))
>>> [array[i:i+w] for i in range(0,len(array)-w+s,s)]
[[0, 1, 2, 3, 4], [3, 4, 5, 6, 7], [6, 7, 8, 9, 10]]

>>> array = list(range(12))
>>> [array[i:i+w] for i in range(0,len(array)-w+s,s)]
[[0, 1, 2, 3, 4], [3, 4, 5, 6, 7], [6, 7, 8, 9, 10], [9, 10, 11]]

more_itertools.windowedでも可能

(LouiS0616さんにコメントで教えていただきました。 ありがとうございます。)
pipでのインストールが必要。

pip install more_itertools

以下のように第二引数がwindow幅、stepがslide幅に対応している。

>>> import more_itertools
>>> array = list(range(12))
>>> list(more_itertools.windowed(array,5,step = 3))
[(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (6, 7, 8, 9, 10), (9, 10, 11, None, None)]

こんな便利な関数があったとは驚き。

以上。

8
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?