回答編集履歴
2
追記(質問が変更されたので)
test
CHANGED
@@ -77,3 +77,61 @@
|
|
77
77
|
# array([1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 1, 2, 3])
|
78
78
|
|
79
79
|
```
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
## 追記(質問が変更されたので)
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
```python
|
88
|
+
|
89
|
+
def get_between_zeros(arr, N, return_index=False):
|
90
|
+
|
91
|
+
arr = np.r_[arr, np.zeros(N, dtype=int)]
|
92
|
+
|
93
|
+
is_nonzero = arr != 0
|
94
|
+
|
95
|
+
s = is_nonzero.argmax()
|
96
|
+
|
97
|
+
ln = np.convolve(is_nonzero[s:], np.ones(N, dtype=int), 'valid').argmin()
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
if return_index:
|
102
|
+
|
103
|
+
return arr[s:s+ln], (s, s+ln)
|
104
|
+
|
105
|
+
else:
|
106
|
+
|
107
|
+
return arr[s:s+ln]
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
|
112
|
+
|
113
|
+
a = np.array([0, 1, 0, 10, 0, 0, 0, 11, 12, 0, 0, 0])
|
114
|
+
|
115
|
+
|
116
|
+
|
117
|
+
outs = []
|
118
|
+
|
119
|
+
for i in range(a.size):
|
120
|
+
|
121
|
+
out, (s, e) = get_between_zeros(a, 3, True)
|
122
|
+
|
123
|
+
outs.append(out.mean())
|
124
|
+
|
125
|
+
a[:e] = 0
|
126
|
+
|
127
|
+
if a.sum() == 0:
|
128
|
+
|
129
|
+
break
|
130
|
+
|
131
|
+
|
132
|
+
|
133
|
+
outs
|
134
|
+
|
135
|
+
# [3.6666666666666665, 11.5]
|
136
|
+
|
137
|
+
```
|
1
詳細に
test
CHANGED
@@ -4,17 +4,43 @@
|
|
4
4
|
|
5
5
|
|
6
6
|
|
7
|
+
def get_between_zeros(arr, N):
|
8
|
+
|
9
|
+
"""最初に現れた0でない値から、その次の0がN連続するまでの間を取得
|
10
|
+
|
11
|
+
"""
|
12
|
+
|
7
|
-
a = np.arr
|
13
|
+
arr = np.r_[arr, np.zeros(N, dtype=int)] # N連続0がない場合用
|
14
|
+
|
15
|
+
is_nonzero = arr != 0
|
8
16
|
|
9
17
|
|
10
18
|
|
11
|
-
|
19
|
+
# 始点=最初に現れた0以外の値の位置
|
12
20
|
|
13
|
-
s = is_nonzero.argmax()
|
21
|
+
s = is_nonzero.argmax()
|
14
22
|
|
15
|
-
|
23
|
+
# 始点より後ろで初めて0がN連続する箇所の位置
|
16
24
|
|
25
|
+
ln = np.convolve(is_nonzero[s:], np.ones(N, dtype=int), 'valid').argmin()
|
26
|
+
|
17
|
-
|
27
|
+
return arr[s:s+ln]
|
28
|
+
|
29
|
+
```
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
↓例
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
```python
|
38
|
+
|
39
|
+
a = np.array([0, 0, 1, 0, 14, 0, 0, 0])
|
40
|
+
|
41
|
+
N = 3
|
42
|
+
|
43
|
+
out = get_between_zeros(a, N)
|
18
44
|
|
19
45
|
|
20
46
|
|
@@ -27,3 +53,27 @@
|
|
27
53
|
# 5.0
|
28
54
|
|
29
55
|
```
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
```python
|
60
|
+
|
61
|
+
a = np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 1, 2, 3])
|
62
|
+
|
63
|
+
get_between_zeros(a, 1)
|
64
|
+
|
65
|
+
# array([1, 2, 3])
|
66
|
+
|
67
|
+
get_between_zeros(a, 2)
|
68
|
+
|
69
|
+
# array([1, 2, 3, 0, 1, 2, 3])
|
70
|
+
|
71
|
+
get_between_zeros(a, 3)
|
72
|
+
|
73
|
+
# array([1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3])
|
74
|
+
|
75
|
+
get_between_zeros(a, 4)
|
76
|
+
|
77
|
+
# array([1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 1, 2, 3])
|
78
|
+
|
79
|
+
```
|