每隔n次删除numpy数组中的一系列元素 [英] Delete a series of elements every nth time in numpy array

查看:79
本文介绍了每隔n次删除numpy数组中的一系列元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何删除numpy数组中的每个第4个元素:

I know how to delete every 4th element in a numpy array:

frame = np.delete(frame,np.arange(4,frame.size,4))

现在我想知道是否有一个简单的命令可以删除每n个(例如4个)乘以3个值.

Now I want to know if there is a simple command that can delete every nth (e.g 4) times 3 values.

一个基本示例:

输入:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ....]

input: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20....]

会导致:

输出:[1,2,3,7,8,9,13,14,15,19,20,....]

output: [1,2,3,7,8,9,13,14,15,19,20,....]

我希望有一个简单的numpy/python功能,而不是编写一个必须在向量上进行迭代的函数(因为在我看来,这很长,...).

I was hoping for a simple numpy / python functionality, rather than writing a function that has to iterate over the vector (cause it is quite long in my case,...).

谢谢您的帮助

推荐答案

使用布尔索引的方法:

def block_delete(a, n, m):  #keep n, remove m
    mask = np.tile(np.r_[np.ones(n), np.zeros(m)].astype(bool), a.size // (n + m) + 1)[:a.size]
    return a[mask]

与@Divakar比较:

Compare with @Divakar:

def mod_delete(a, n, m):
    return a[np.mod(np.arange(a.size), n + m) < n]

a = np.arange(19) + 1

%timeit block_delete(a, 3, 4)
10000 loops, best of 3: 50.6 µs per loop

%timeit mod_delete(a, 3, 4)
The slowest run took 9.37 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.69 µs per loop

让我们尝试更长的数组:

Let's try a longer array:

a = np.arange(999) + 1

%timeit block_delete(a, 3, 4)
The slowest run took 4.61 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 54.8 µs per loop

%timeit mod_delete(a, 3, 4)
The slowest run took 5.13 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 14.5 µs per loop

还有更长的时间:

a = np.arange(999999) + 1

%timeit block_delete(a, 3, 4)
100 loops, best of 3: 3.93 ms per loop

%timeit mod_delete(a, 3, 4)
100 loops, best of 3: 12.3 ms per loop

那么哪个更快取决于阵列的大小

So which is faster will depend on the size of your array

这篇关于每隔n次删除numpy数组中的一系列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆