[英]Filling zeros in numpy array that are between non-zero elements with the same value
我有一個帶整數的一維numpy numpy數組,當且僅當下一個非零值相同時,我才想用先前的非零值替換零。
例如,一個數組:
in: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1])
out: [1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1]
應該成為
out: [1,1,1,1,0,0,2,0,3,3,3,3,3,1,1,1]
有矢量化的方法可以做到這一點嗎? 我在這里找到了一種填充零值的方法,但是沒有找到例外的方法,即不填充具有不同值的整數內的零。
這是一種矢量化方法,該方法從NumPy based forward-filling
方法中獲取此解決方案中的正向填充部分以及masking
和slicing
靈感-
def forward_fill_ifsame(x):
# Get mask of non-zeros and then use it to forward-filled indices
mask = x!=0
idx = np.where(mask,np.arange(len(x)),0)
np.maximum.accumulate(idx,axis=0, out=idx)
# Now we need to work on the additional requirement of filling only
# if the previous and next ones being same
# Store a copy as we need to work and change input data
x1 = x.copy()
# Get non-zero elements
xm = x1[mask]
# Off the selected elements, we need to assign zeros to the previous places
# that don't have their correspnding next ones different
xm[:-1][xm[1:] != xm[:-1]] = 0
# Assign the valid ones to x1. Invalid ones become zero.
x1[mask] = xm
# Use idx for indexing to do the forward filling
out = x1[idx]
# For the invalid ones, keep the previous masked elements
out[mask] = x[mask]
return out
樣品運行-
In [289]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1])
In [290]: np.vstack((x, forward_fill_ifsame(x)))
Out[290]:
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 3, 1, 0, 1],
[1, 1, 1, 1, 0, 0, 2, 0, 3, 3, 3, 3, 3, 1, 1, 1]])
In [291]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,1,1,0,1])
In [292]: np.vstack((x, forward_fill_ifsame(x)))
Out[292]:
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 1, 1]])
In [293]: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,1,1,0,2])
In [294]: np.vstack((x, forward_fill_ifsame(x)))
Out[294]:
array([[1, 0, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 2],
[1, 1, 1, 1, 0, 0, 2, 0, 3, 0, 0, 0, 1, 1, 0, 2]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.