用最后一个非零值填充1d numpy数组的零值

编程入门 行业动态 更新时间:2024-10-12 08:22:53
本文介绍了用最后一个非零值填充1d numpy数组的零值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个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数组的零值

本文发布于:2023-10-27 04:31:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   非零值   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!