Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@osanshouo

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

More than 1 year has passed since last update.

本論

問題

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.

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

0
Help us understand the problem. What is going on with this article?
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.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?