8

私はnumpy配列を持っています:

a = [3., 0., 4., 2., 0., 0., 0.]

これから作成された新しい配列が必要です。ゼロ以外の要素はゼロの値に変換され、ゼロ要素は連続するゼロの数に等しい単一の数値に変換されます。

b = [0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 3.]

配列の要素数が 100 万を超えるため、これをベクトル化する方法を探しています。どんな助けでも大歓迎です。

4

2 に答える 2

8

1) 連続するすべてのゼロを見つけてカウントし、2) 出力配列のサイズを計算してゼロで初期化し、3) パート 1 のカウントを正しい場所に配置します。

def cz(a):
    a = np.asarray(a, int)

    # Find where sequences of zeros start and end
    wz = np.zeros(len(a) + 2, dtype=bool)
    wz[1:-1] = a == 0
    change = wz[1:] != wz[:-1]
    edges = np.where(change)[0]
    # Take the difference to get the number of zeros in each sequence
    consecutive_zeros = edges[1::2] - edges[::2]

    # Figure out where to put consecutive_zeros
    idx = a.cumsum()
    n = idx[-1] if len(idx) > 0 else 0
    idx = idx[edges[::2]]
    idx += np.arange(len(idx))

    # Create output array and populate with values for consecutive_zeros
    out = np.zeros(len(consecutive_zeros) + n)
    out[idx] = consecutive_zeros
    return out
于 2013-10-17T00:57:37.807 に答える
4

いくつかの種類の場合:

a = np.array([3., 0., 4., 2., 0., 0., 0.],dtype=np.int)

inds = np.cumsum(a)

#Find first occurrences and values thereof.
uvals,zero_pos = np.unique(inds,return_index=True)
zero_pos = np.hstack((zero_pos,a.shape[0]))+1

#Gets zero lengths
values =  np.diff(zero_pos)-1
mask = (uvals!=0)

#Ignore where we have consecutive values
zero_inds = uvals[mask]
zero_inds += np.arange(zero_inds.shape[0])

#Create output array and apply zero values
out = np.zeros(inds[-1] + zero_inds.shape[0])
out[zero_inds] = values[mask]

out
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  3.]

np.unique主に、配列が単調に増加している限り、配列の最初の出現を見つけるために使用できるという点で異なります。

于 2013-10-17T01:57:12.700 に答える