Help us understand the problem. What is going on with this article?

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

本論

問題

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.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした