2

我有两个数组:

 a = numpy.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
 label = numpy.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'])

我正在寻找的是根据以下条件填充零:

If the label[i-1] != label[i]:
   pad several zeros (say, 3) to the 'a' array at the same 'i' location

所以,我想要的结果是:

a = numpy.array([ 1,  2,  3,  4,  5,  6,  7, 0, 0, 0, 8,  9, 10])
label = numpy.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'])

如您所见,数组a现在在 value 之后有 3 个零7,它们由标签值更改的条件填充。

我尝试了以下代码:

for i in range(len(a)):
    if label[i-1] != label[i]:         
        a = numpy.pad(a, (0,3), 'constant')
    else:
       pass

但是,零被填充在a数组的末尾。正如我怀疑的那样,我应该将填充操作等同于同一个数组,因为它在 for 循环中发生了变化。

4

4 回答 4

2

这是一个基于 numpy 的方法:

def pad_at_diff(x, y, n):   
    # boolean mask where diffs occur 
    m = np.r_[False, y[:-1]!= y[1:]]
    # output array, expanded taking into account 
    # zeros to add
    x_pad = np.zeros(len(x)+n*len(m[m]))
    # assign at according indices adding cumsum of m
    x_pad[np.arange(len(x))+np.cumsum(m)*n] = x
    return x_pad

a = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
label = np.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'])
pad_at_diff(a, label, 3)
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  0.,  0.,  0.,  8.,  9., 10.])

或者对于另一个例子:

a = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10,11,12])
label = np.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'])
pad_at_diff(a, label, 3)
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  0.,  0.,  0.,  8.,  9., 10.,
        0.,  0.,  0., 11., 12.])
于 2020-07-20T11:09:17.980 回答
1
  • 您需要基于 a 进行更改,label因此您需要遍历label,而不是通过a
  • 现在你应该在中添加i != 0条件,if否则如果第一个和最后一个相同,你也会因为 -1返回到最后一个元素而受到惩罚。
import numpy as np
a = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
label = np.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'])

offset = 0
for i in range(len(label)):
    if i != 0 and label[i-1] != label[i]:
        len_ = 2 # no of 0's you want to add
        a = np.insert(a, i + offset, np.array([0] * len_))
        offset += len_
print(a)

输出:

[ 1  2  3  4  5  6  7  0  0  8  9 10]
于 2020-07-20T11:00:13.610 回答
1

这是你想要的吗?

>>> for i in range(a.size-1):
        if label[i]!=label[i+1]:
            np.insert(a,i+1,[0]*3)

这就是我得到的:

array([ 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 8, 9, 10])

if参考了你的情况。

于 2020-07-20T11:11:23.373 回答
1

np 的 pad 函数添加到数组的末尾。我认为您正在寻找的是插入。插入的问题是,一旦您插入值,您的索引就会随着循环发生变化。如果你从后面循环,虽然它有效:

import numpy as np
a = np.array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
label = np.array(['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'])

prev=None
for i,ele in enumerate(label[::-1]):
   if prev:
      if ele!=prev:
         a=np.insert(a,-i, [0,0,0])
         print(ele)
   prev=ele
于 2020-07-20T11:12:32.213 回答