LoginSignup
4
1

More than 3 years have passed since last update.

[Python/numpy] 隣接する要素との平均を計算する

Last updated at Posted at 2019-10-21

本論

問題

numpy で隣の要素との平均を計算したいことがたまにあります. つまり, 長さ n の ndarray, 例えば

x = np.arange(n)

が与えられたとき, 次の長さ n-1 の ndarray が欲しいのです.

ave = ndarray([
    (x[0]+x[1])/2.,
    (x[1]+x[2])/2.,
    ...,
    (x[n-2]+x[n-1])/2.,
])

解法

これは numpy 1.12 で導入された numpy.roll 関数を使うのが最適解だと思います.

x1 = np.roll(x, -1)  # = np.ndarray([ x[1], x[2], ..., x[n-1], x[0] ])
ave = (x + x1)/2.    # これは長さ n の ndarray で最後の要素 (x[0]+x[n-1])/2. は要らない
ave = ave[:-1]       # これが欲しいもの

np.roll の第 2 引数の符号に注意してください.

参考文献

追記

コメントで @shiracamus さんに

ave = (x[1:]+x[:-1])/2.

で十分と指摘していただきました.

4
1
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
4
1