擅长:python、mysql、java
<p><strong>方法#1</strong></p>
<p>这里有一个简单的方法-</p>
<pre><code>In [23]: ids = np.r_[0,b[:-1]!=b[1:]].cumsum()
In [24]: np.where(b==1,a.groupby(ids).transform('mean'),a)
Out[24]:
array([1. , 4. , 4. , 4. , 7. ,
5. , 6. , 6. , 6. , 6. ,
7. , 3.33333333, 3.33333333, 3.33333333, 6. ,
9. ])
</code></pre>
<p><strong>方法#2</strong></p>
<p>对于性能,我们可以利用<a href="https://numpy.org/doc/stable/reference/generated/numpy.bincount.html" rel="nofollow noreferrer">^{<cd1>}</a>-</p>
<pre><code>In [47]: v = np.bincount(ids,a)/np.bincount(ids)
In [48]: np.where(b==1,v[ids],a)
Out[48]:
array([1. , 4. , 4. , 4. , 7. ,
5. , 6. , 6. , 6. , 6. ,
7. , 3.33333333, 3.33333333, 3.33333333, 6. ,
9. ])
</code></pre>