二次抽样中numpy的阵列的每个第n个条目 [英] subsampling every nth entry in a numpy array

查看:177
本文介绍了二次抽样中numpy的阵列的每个第n个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与numpy的初学者,我试图从长numpy的阵列中提取一些数据。我需要做的是从我的数组定义的位置开始,然后二次采样从该位置的每第n个数据点,直到我的数组的末尾。

基本上,如果我有

  A = [1,2,3,4,1,2,3,4,1,2,3,4 ......]

我想从那里这个二次抽样在开始[1] ,然后品尝每第四点,产生类似

  B = [2,2,2 ...]


解决方案

您可以使用的 numpy的的切片,只需启动:停止:步骤

 >>> XS
阵列([1,2,3,4,1,2,3,4,1,2,3,4])
>>> XS [1:4]
阵列([2,2,2])

这将创建原始数据的视图的,所以它的恒定的时间的。这也将反映改变原来的阵列和保持整个原始数组存储:

 >>>一个
阵列([1,2,3,4,5])
>>> B = A [:: 2]#O(1),恒定的时间
>>> B〔:] = 0#修改视图改变原始数组
>>>一个#原数组被修改
阵列([0,2,0,4,0])

因此​​,如果上述任何一种东西是一个问题,你可以复制明确:

 >>>一个
阵列([1,2,3,4,5])
>>> B = A [:: 2] .copy()#明确的副本,为O(n)
>>> B〔:] = 0#修改副本
>>>一个#原来是完好无损
阵列([1,2,3,4,5])

这是不恒定的时间,但结果是不依赖于原始数组。副本也连续的存储器,它可以使在其上的一些操作速度更快。

I am a beginner with numpy, and I am trying to extract some data from a long numpy array. What I need to do is start from a defined position in my array, and then subsample every nth data point from that position, until the end of my array.

basically if I had

a = [1,2,3,4,1,2,3,4,1,2,3,4....] 

I want to subsample this to start at a[1] and then sample every fourth point from there, to produce something like

b = [2,2,2.....]

解决方案

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

这篇关于二次抽样中numpy的阵列的每个第n个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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