简体   繁体   English

扩展切片numpy数组的步骤

[英]Extending steps for slicing numpy arrays

My question is similar to this: subsampling every nth entry in a numpy array 我的问题类似于: 在numpy数组中对每个第n个条目进行子采样

Let's say I have an array as given below: a = [1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4....] 假设我有一个如下所示的数组:a = [1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4 .. ..]

How can I extend the slice such that I slice three elements at specific intervals? 如何扩展切片,以便按特定间隔切片三个元素? Ie how can I slice 2s from the array? 即我如何从数组切片2? I believe basic slicing does not work in this case. 我认为在这种情况下基本切片不起作用。

You can do this through individual indexing. 您可以通过单独索引来完成此操作。

We want to start from the element at index 1, take 3 elements and then skip 3 elements: 我们想从索引1处的元素开始,取3个元素,然后跳过3个元素:

a = np.array([1, 2, 2, 2, 3, 4, 1, 2, 2, 2, 3, 4, 1, 2, 2, 2, 3, 4])

start = 1
take = 3
skip = 3

indices = np.concatenate([np.arange(i, i + take) for i in range(start, len(a), take + skip)])

print(indices)
print(a[indices])

Output: 输出:

[ 1  2  3  7  8  9 13 14 15]
[2 2 2 2 2 2 2 2 2]

The simplest here seems: 这里最简单的似乎是:

 a = np.array([1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4])
 a.reshape(-1,6)[1:4].ravel()

or if a doesn't chunk well : 或者如果a不好的话:

period = 6
a.resize(np.math.ceil(a.size/period),period)
a[:,1:4].ravel()

Here's a vectorized one with masking - 这是一个带masking的矢量化 -

def take_sliced_regions(a, start, take, skip):
    r = np.arange(len(a))-start
    return a[r%(take+skip)<take]

Sample run - 样品运行 -

In [90]: a = np.array([1,2,2,2,3,4,1,2,2,2,3,4,1,2,2,2,3,4,1,2])

In [91]: take_sliced_regions(a, start=1, take=3, skip=3)
Out[91]: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM