假设我们有一个1d numpy数组,其中填充了一些int值.假设其中一些是0.
Let's say we have a 1d numpy array filled with some int values. And let's say that some of them are 0.
有什么方法可以利用numpy数组的功效,用找到的最后一个非零值来填充所有0值?
Is there any way, using numpy array's power, to fill all the 0 values with the last non-zero values found?
例如:
arr = np.array([1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2]) fill_zeros_with_last(arr) print arr [1 1 1 2 2 4 6 8 8 8 8 8 2]使用此功能的一种方法是
A way to do it would be with this function:
def fill_zeros_with_last(arr): last_val = None # I don't really care about the initial value for i in range(arr.size): if arr[i]: last_val = arr[i] elif last_val is not None: arr[i] = last_val但是,这是使用原始的python for循环,而不是利用numpy和scipy的功能.
However, this is using a raw python for loop instead of taking advantage of the numpy and scipy power.
如果我们知道可能有相当数量的连续零,则可以使用基于numpy.roll的值.问题在于连续零的数量可能很大...
If we knew that a reasonably small number of consecutive zeros are possible, we could use something based on numpy.roll. The problem is that the number of consecutive zeros is potentially large...
有什么想法吗?还是我们应该直接去Cython?
Any ideas? or should we go straight to Cython?
我会说很久以前,我在stackoverflow中发现了一个问题,问类似或类似的问题.我找不到它. :-(
I would say long ago I found a question in stackoverflow asking something like this or very similar. I wasn't able to find it. :-(
也许我错过了正确的搜索字词,对不起,重复.也许这只是我的想象...
Maybe I missed the right search terms, sorry for the duplicate then. Maybe it was just my imagination...
推荐答案以下是使用np.maximum.accumulate的解决方案:
Here's a solution using np.maximum.accumulate:
def fill_zeros_with_last(arr): prev = np.arange(len(arr)) prev[arr == 0] = 0 prev = np.maximum.accumulate(prev) return arr[prev]我们构造一个数组prev,该数组的长度与arr相同,并且prev[i]是数组 i 的最后一个非零条目的索引. arr.例如,如果:
We construct an array prev which has the same length as arr, and such that prev[i] is the index of the last non-zero entry before the i-th entry of arr. For example, if:
>>> arr = np.array([1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2])然后prev看起来像:
array([ 0, 0, 0, 3, 3, 5, 6, 7, 7, 7, 7, 7, 12])然后我们只用prev索引到arr中,就可以得到结果.测试:
Then we just index into arr with prev and we obtain our result. A test:
>>> arr = np.array([1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2]) >>> fill_zeros_with_last(arr) array([1, 1, 1, 2, 2, 4, 6, 8, 8, 8, 8, 8, 2])注意:请仔细了解当数组的第一个条目为零时这将做什么:
Note: Be careful to understand what this does when the first entry of your array is zero:
>>> fill_zeros_with_last(np.array([0,0,1,0,0])) array([0, 0, 1, 1, 1])更多推荐
用最后一个非零值填充1d numpy数组的零值
发布评论