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

0と0以外の連続区間を見つける

More than 1 year has passed since last update.

はじめに

こんなデータのときにゼロやゼロ以外の値となるindexのそれぞれの山の始まりと終わりを知りたいときがある。(私はよくある)

Unknown-2.png

もっと早くていい方法とか、実は関数あるよとかありそうなのだけど、色々と使いまわしたい自分のためにのんびり作ったものを置いておく。

使用例

実際に使うとこんな感じ

data = [12,11,0,0,0,11,12,13,14,12,13,0,0,0,0,0,20,17,16,14,16,0,0,1,1,0,0,10,11,0]
a = np.array(data)
find_zero = False #ゼロを探すときはTrue
res = start_end_index(a, find_zero)
#結果
#区間の始まりのindex
>>> print(res[0])
[0, 5, 16, 23, 27]

#区間の終わりのindex
>>> print(res[1])
[1, 10, 20, 24, 28]

#たとえばひと山の合計値を出すなら
for i in range(len(res[0])):
    print(sum(a[res[0][i]:res[1][i]+1]))

関数

start_end_index
def start_end_index(a, find_zero):
    if find_zero == True:
        index = list(np.where(a == 0))[0]
    else:
        index = list(np.where(a != 0))[0]
    start = []
    end = []

    for i in range(len(index)-1):
        print(index[i], index[i+1])
        if (i == 0):
            start.append(index[0])

        if index[i+1] - index[i] > 1:
            end.append(index[i])
            start.append(index[i+1])

        if (i+1 == len(index)-1):
            end.append(index[i+1])

    return start,end
Why do not you register as a user and use Qiita more conveniently?
  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
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