改变numpy数组中的元素

时间:2013-10-16 23:51:24

标签: numpy

我有一个numpy数组:

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

我想要一个新的数组,由此创建,其中非零元素以零的形式转换为它们的值,零元素转换为单个数字,等于连续的零数,即:

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

寻找一种矢量化的方法,因为数组将具有> 100万元素。  任何帮助非常感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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来查找数组的第一次出现,只要它是单调递增的。

相关问题